Java Code Examples for java.security.Security

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project gitblit, under directory /src/com/gitblit/.

Source file: MakeCertificate.java

  22 
vote

public static void generateSelfSignedCertificate(String hostname,File keystore,String keystorePassword){
  try {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPairGenerator kpGen=KeyPairGenerator.getInstance("RSA","BC");
    kpGen.initialize(1024,new SecureRandom());
    KeyPair pair=kpGen.generateKeyPair();
    X500NameBuilder builder=new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.OU,Constants.NAME);
    builder.addRDN(BCStyle.O,Constants.NAME);
    builder.addRDN(BCStyle.CN,hostname);
    Date notBefore=new Date(System.currentTimeMillis() - TimeUtils.ONEDAY);
    Date notAfter=new Date(System.currentTimeMillis() + 10 * TimeUtils.ONEYEAR);
    BigInteger serial=BigInteger.valueOf(System.currentTimeMillis());
    X509v3CertificateBuilder certGen=new JcaX509v3CertificateBuilder(builder.build(),serial,notBefore,notAfter,builder.build(),pair.getPublic());
    ContentSigner sigGen=new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(pair.getPrivate());
    X509Certificate cert=new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());
    KeyStore store=KeyStore.getInstance("JKS");
    if (keystore.exists()) {
      FileInputStream fis=new FileInputStream(keystore);
      store.load(fis,keystorePassword.toCharArray());
      fis.close();
    }
 else {
      store.load(null);
    }
    store.setKeyEntry(hostname,pair.getPrivate(),keystorePassword.toCharArray(),new java.security.cert.Certificate[]{cert});
    FileOutputStream fos=new FileOutputStream(keystore);
    store.store(fos,keystorePassword.toCharArray());
    fos.close();
  }
 catch (  Throwable t) {
    t.printStackTrace();
    throw new RuntimeException("Failed to generate self-signed certificate!",t);
  }
}
 

Example 2

From project penrose-server, under directory /core/src/java/org/safehaus/penrose/module/.

Source file: EncryptionModule.java

  20 
vote

public void init() throws Exception {
  verbose=Boolean.parseBoolean(getParameter("verbose"));
  if (verbose) {
    Provider[] providers=Security.getProviders();
    for (    Provider p : providers) {
      System.out.println("[EncryptionModule] " + p.getName() + " "+ p.getVersion()+ " security provider available.");
    }
  }
  String ciphers=getParameter("ciphers");
  if (ciphers != null) {
    StringTokenizer st=new StringTokenizer(ciphers,",");
    while (st.hasMoreTokens()) {
      String name=st.nextToken().trim();
      checkCipher(name);
    }
  }
  String messageDigests=getParameter("messageDigests");
  if (messageDigests != null) {
    StringTokenizer st=new StringTokenizer(messageDigests,",");
    while (st.hasMoreTokens()) {
      String name=st.nextToken().trim();
      checkMessageDigest(name);
    }
  }
}
 

Example 3

From project ajah, under directory /ajah-crypto/src/main/java/com/ajah/crypto/.

Source file: Crypto.java

  19 
vote

private static void listProviders(){
  log.info("Supported providers:");
  for (  final Provider provider : Security.getProviders()) {
    System.out.println("\t" + provider);
    for (    final Provider.Service service : provider.getServices()) {
      System.out.println("\t\t" + service.getAlgorithm());
    }
  }
}
 

Example 4

From project android-client_1, under directory /src/org/apache/harmony/javax/security/sasl/.

Source file: Sasl.java

  19 
vote

/** 
 * This method forms the list of SaslClient/SaslServer factories which are implemented in used providers
 */
private static Collection<?> findFactories(String service){
  HashSet<Object> fact=new HashSet<Object>();
  Provider[] pp=Security.getProviders();
  if ((pp == null) || (pp.length == 0)) {
    return fact;
  }
  HashSet<String> props=new HashSet<String>();
  for (int i=0; i < pp.length; i++) {
    String prName=pp[i].getName();
    Enumeration<Object> keys=pp[i].keys();
    while (keys.hasMoreElements()) {
      String s=(String)keys.nextElement();
      if (s.startsWith(service)) {
        String prop=pp[i].getProperty(s);
        try {
          if (props.add(prName.concat(prop))) {
            fact.add(newInstance(prop,pp[i]));
          }
        }
 catch (        SaslException e) {
          e.printStackTrace();
        }
      }
    }
  }
  return fact;
}
 

Example 5

From project AsmackService, under directory /src/org/apache/harmony/javax/security/sasl/.

Source file: Sasl.java

  19 
vote

/** 
 * This method forms the list of SaslClient/SaslServer factories which are implemented in used providers
 */
private static Collection<?> findFactories(String service){
  HashSet<Object> fact=new HashSet<Object>();
  Provider[] pp=Security.getProviders();
  if ((pp == null) || (pp.length == 0)) {
    return fact;
  }
  HashSet<String> props=new HashSet<String>();
  for (int i=0; i < pp.length; i++) {
    String prName=pp[i].getName();
    Enumeration<Object> keys=pp[i].keys();
    while (keys.hasMoreElements()) {
      String s=(String)keys.nextElement();
      if (s.startsWith(service)) {
        String prop=pp[i].getProperty(s);
        try {
          if (props.add(prName.concat(prop))) {
            fact.add(newInstance(prop,pp[i]));
          }
        }
 catch (        SaslException e) {
          e.printStackTrace();
        }
      }
    }
  }
  return fact;
}
 

Example 6

From project avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/ipc/.

Source file: TestNettyServerWithSSL.java

  19 
vote

private String getAlgorithm(){
  String algorithm=Security.getProperty("ssl.KeyManagerFactory.algorithm");
  if (algorithm == null) {
    algorithm="SunX509";
  }
  return algorithm;
}
 

Example 7

From project chililog-server, under directory /src/main/java/org/chililog/server/pubsub/jsonhttp/.

Source file: JsonHttpSslContextManager.java

  19 
vote

/** 
 * Constructor for singleton
 */
private JsonHttpSslContextManager(){
  try {
    String algorithm=Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
      algorithm="SunX509";
    }
    SSLContext serverContext=null;
    try {
      KeyStore ks=KeyStore.getInstance("JKS");
      FileInputStream fin=new FileInputStream(AppProperties.getInstance().getPubSubJsonHttpKeyStorePath());
      ks.load(fin,AppProperties.getInstance().getPubSubJsonHttpKeyStorePassword().toCharArray());
      KeyManagerFactory kmf=KeyManagerFactory.getInstance(algorithm);
      kmf.init(ks,AppProperties.getInstance().getPubSubJsonHttpKeyStoreKeyPassword().toCharArray());
      serverContext=SSLContext.getInstance(PROTOCOL);
      serverContext.init(kmf.getKeyManagers(),null,null);
    }
 catch (    Exception e) {
      throw new Error("Failed to initialize the server-side SSLContext",e);
    }
    _serverContext=serverContext;
    SSLContext clientContext=null;
    try {
      clientContext=SSLContext.getInstance(PROTOCOL);
      clientContext.init(null,JsonHttpSSLTrustManager.getInstance().getTrustManagers(),null);
    }
 catch (    Exception e) {
      throw new Error("Failed to initialize the client-side SSLContext",e);
    }
    _clientContext=clientContext;
    return;
  }
 catch (  Exception ex) {
    _logger.error("Error initializing SslContextManager. " + ex.getMessage(),ex);
    System.exit(1);
  }
}
 

Example 8

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.

Source file: IdentityApplic.java

  19 
vote

public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
  prop=new Properties();
  prop.load(new FileInputStream("ferryinpres.properties"));
  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  Socket sock=new Socket(prop.getProperty("IDENTITY_SERVER"),Integer.parseInt(prop.getProperty("IDENTITY_PORT")));
  ObjectOutputStream out=new ObjectOutputStream(sock.getOutputStream());
  ObjectInputStream in=new ObjectInputStream(sock.getInputStream());
  SecretKey sessionKey=keyExchange(in,out);
  Cipher cryptor=Cipher.getInstance("DES/ECB/PKCS5Padding");
  cryptor.init(Cipher.ENCRYPT_MODE,sessionKey);
  Cipher decryptor=Cipher.getInstance("DES/ECB/PKCS5Padding");
  decryptor.init(Cipher.DECRYPT_MODE,sessionKey);
  login(in,out,cryptor,decryptor);
}
 

Example 9

From project GNDMS, under directory /kit/test-src/de/zib/gndms/kit/security/test/.

Source file: PemReaderTest.java

  19 
vote

public static void main(String[] args) throws Exception {
  if (args.length != 2) {
    System.err.println("usage: PemReaderTest <pem-location> <pk-pass-phase>");
    System.exit(1);
  }
  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  CertStuffHolder certStuff=readKeyPair(new File(args[0]),args[1].toCharArray());
  System.out.println(certStuff.getKeyPair());
  System.exit(0);
}
 

Example 10

From project http-client, under directory /src/main/java/com/biasedbit/http/ssl/.

Source file: BogusSslContextFactory.java

  19 
vote

public BogusSslContextFactory(){
  String algorithm=Security.getProperty("ssl.KeyManagerFactory.algorithm");
  if (algorithm == null) {
    algorithm="X509";
  }
  SSLContext tmpServerContext;
  SSLContext tmpClientContext;
  try {
    KeyStore ks=KeyStore.getInstance("JKS");
    ks.load(BogusKeyStore.asInputStream(),BogusKeyStore.getKeyStorePassword());
    KeyManagerFactory kmf=KeyManagerFactory.getInstance(algorithm);
    kmf.init(ks,BogusKeyStore.getCertificatePassword());
    tmpServerContext=SSLContext.getInstance(PROTOCOL);
    tmpServerContext.init(kmf.getKeyManagers(),BogusTrustManagerFactory.getTrustManagers(),null);
  }
 catch (  Exception e) {
    throw new Error("Failed to initialize the server-side SSLContext",e);
  }
  try {
    tmpClientContext=SSLContext.getInstance(PROTOCOL);
    tmpClientContext.init(null,BogusTrustManagerFactory.getTrustManagers(),null);
  }
 catch (  Exception e) {
    throw new Error("Failed to initialize the client-side SSLContext",e);
  }
  serverContext=tmpServerContext;
  clientContext=tmpClientContext;
}
 

Example 11

From project IOCipherServer, under directory /src/info/guardianproject/iocipher/server/.

Source file: KeyStoreGenerator.java

  19 
vote

public static void generateKeyStore(File keyStoreFile,String alias,int keyLength,String password,String cn,String o,String ou,String l,String st,String c) throws Exception {
  final java.security.KeyPairGenerator rsaKeyPairGenerator=java.security.KeyPairGenerator.getInstance("RSA");
  rsaKeyPairGenerator.initialize(keyLength);
  final KeyPair rsaKeyPair=rsaKeyPairGenerator.generateKeyPair();
  Provider[] ps=Security.getProviders();
  final KeyStore ks=KeyStore.getInstance("BKS");
  ks.load(null);
  final RSAPublicKey rsaPublicKey=(RSAPublicKey)rsaKeyPair.getPublic();
  char[] pw=password.toCharArray();
  final RSAPrivateKey rsaPrivateKey=(RSAPrivateKey)rsaKeyPair.getPrivate();
  final java.security.cert.X509Certificate certificate=makeCertificate(rsaPrivateKey,rsaPublicKey,cn,o,ou,l,st,c);
  final java.security.cert.X509Certificate[] certificateChain={certificate};
  ks.setKeyEntry(alias,rsaKeyPair.getPrivate(),pw,certificateChain);
  final FileOutputStream fos=new FileOutputStream(keyStoreFile);
  ks.store(fos,pw);
  fos.close();
}
 

Example 12

From project jboss-sasl, under directory /src/test/java/org/jboss/sasl/test/.

Source file: BaseTestCase.java

  19 
vote

@BeforeClass public static void registerProvider(){
  AccessController.doPrivileged(new PrivilegedAction<Integer>(){
    public Integer run(){
      return Security.insertProviderAt(jbossSaslProvider,1);
    }
  }
);
}
 

Example 13

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/security/.

Source file: KeyStoreComponent.java

  19 
vote

/** 
 * Loads the key store.
 * @throws KeyStoreManagementException if unable to loads the key store.
 */
private void load() throws KeyStoreManagementException {
  if (keyStore == null) {
    try {
      if (storeType == null) {
        storeType=KeyStore.getDefaultType();
      }
      if (provider == null) {
        keyStore=KeyStore.getInstance(storeType);
      }
 else {
        Instance secProviderInstance=new Instance(provider);
        Provider secProvider=(Provider)secProviderInstance.getObject();
        Security.addProvider(secProvider);
        keyStore=KeyStore.getInstance(storeType,secProvider);
      }
      InputStream ins=getModule() == null ? new FileInputStream(location) : getModule().getResourceAsStream(location);
      if (ins == null) {
        throw new KeyStoreManagementException("No key store found: " + location);
      }
 else {
        keyStore.load(ins,storePass);
        ins.close();
        ins=null;
      }
    }
 catch (    Exception e) {
      throw new KeyStoreManagementException("Unable to initialize the key store",e);
    }
  }
}
 

Example 14

From project JGlobus, under directory /ssl-proxies/src/main/java/org/globus/gsi/util/.

Source file: CertificateUtil.java

  19 
vote

/** 
 * Installs SecureRandom provider.  This function is automatically called when this class is loaded.
 */
public static void installSecureRandomProvider(){
  CoGProperties props=CoGProperties.getDefault();
  String providerName=props.getSecureRandomProvider();
  try {
    Class providerClass=Class.forName(providerName);
    Security.insertProviderAt((Provider)providerClass.newInstance(),1);
  }
 catch (  Exception e) {
    logger.debug("Unable to install PRNG. Using default PRNG.",e);
  }
}
 

Example 15

From project jPOS, under directory /jpos/src/main/java/org/jpos/security/jceadapter/.

Source file: JCEHandler.java

  19 
vote

/** 
 * Registers the JCE provider whose name is providerName and sets it to be the only provider to be used in this instance of the JCEHandler class.
 * @param jceProviderClassName Name of the JCE provider (e.g. "com.sun.crypto.provider.SunJCE" for Sun's implementation, or "org.bouncycastle.jce.provider.BouncyCastleProvider" for bouncycastle.org implementation)
 * @throws JCEHandlerException
 */
public JCEHandler(String jceProviderClassName) throws JCEHandlerException {
  try {
    provider=(Provider)Class.forName(jceProviderClassName).newInstance();
    Security.addProvider(provider);
  }
 catch (  Exception e) {
    throw new JCEHandlerException(e);
  }
}
 

Example 16

From project karaf, under directory /main/src/main/java/org/apache/karaf/main/.

Source file: Main.java

  19 
vote

private static void addSecurityProvider(String provider){
  try {
    Security.addProvider((Provider)Class.forName(provider).newInstance());
  }
 catch (  Throwable t) {
    System.err.println("Unable to register security provider: " + t);
  }
}
 

Example 17

From project LRJavaLib, under directory /src/com/navnorth/learningregistry/.

Source file: LRSigner.java

  19 
vote

/** 
 * Creates a signer, using specified key values
 * @param publicKeyLocation location of the public key to be included in signed envelopes
 * @param privateKey local location or raw value of private key to be used for encoding
 * @param passPhrase pass phrase for signing with the included private key
 */
public LRSigner(String publicKeyLocation,String privateKey,String passPhrase){
  Security.addProvider(new BouncyCastleProvider());
  this.publicKeyLocation=publicKeyLocation.replaceAll("&amp;","&");
  this.privateKey=privateKey;
  this.passPhrase=passPhrase;
  passPhrase=StringUtil.nullifyBadInput(passPhrase);
  publicKeyLocation=StringUtil.nullifyBadInput(publicKeyLocation);
  privateKey=StringUtil.nullifyBadInput(privateKey);
}
 

Example 18

From project Maimonides, under directory /src/com/codeko/apps/maimonides/dnie/.

Source file: DNIe.java

  19 
vote

private KeyStore getKeyStore() throws Exception {
  if (keyStore == null) {
    Provider p=new sun.security.pkcs11.SunPKCS11(new ByteArrayInputStream(DNIe.getConfig()));
    Security.addProvider(p);
    keyStore=KeyStore.getInstance("PKCS11",p);
    try {
      keyStore.load(null,getPin().toCharArray());
    }
 catch (    Exception e) {
      keyStore=null;
      throw e;
    }
  }
  return keyStore;
}
 

Example 19

From project netty, under directory /example/src/main/java/io/netty/example/http/websocketx/sslserver/.

Source file: WebSocketSslServerSslContext.java

  19 
vote

/** 
 * Constructor for singleton
 */
private WebSocketSslServerSslContext(){
  try {
    String algorithm=Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
      algorithm="SunX509";
    }
    SSLContext serverContext;
    try {
      String keyStoreFilePath=System.getProperty("keystore.file.path");
      String keyStoreFilePassword=System.getProperty("keystore.file.password");
      KeyStore ks=KeyStore.getInstance("JKS");
      FileInputStream fin=new FileInputStream(keyStoreFilePath);
      ks.load(fin,keyStoreFilePassword.toCharArray());
      KeyManagerFactory kmf=KeyManagerFactory.getInstance(algorithm);
      kmf.init(ks,keyStoreFilePassword.toCharArray());
      serverContext=SSLContext.getInstance(PROTOCOL);
      serverContext.init(kmf.getKeyManagers(),null,null);
    }
 catch (    Exception e) {
      throw new Error("Failed to initialize the server-side SSLContext",e);
    }
    _serverContext=serverContext;
  }
 catch (  Exception ex) {
    if (logger.isErrorEnabled()) {
      logger.error("Error initializing SslContextManager. " + ex.getMessage(),ex);
    }
    System.exit(1);
  }
}
 

Example 20

From project netty-socketio, under directory /src/main/java/com/corundumstudio/socketio/.

Source file: SocketIOPipelineFactory.java

  19 
vote

private SSLContext createSSLContext(InputStream keyStoreFile,String keyStoreFilePassword) throws Exception {
  String algorithm=Security.getProperty("ssl.KeyManagerFactory.algorithm");
  if (algorithm == null) {
    algorithm="SunX509";
  }
  KeyStore ks=KeyStore.getInstance("JKS");
  ks.load(keyStoreFile,keyStoreFilePassword.toCharArray());
  KeyManagerFactory kmf=KeyManagerFactory.getInstance(algorithm);
  kmf.init(ks,keyStoreFilePassword.toCharArray());
  SSLContext serverContext=SSLContext.getInstance("TLS");
  serverContext.init(kmf.getKeyManagers(),null,null);
  return serverContext;
}
 

Example 21

From project Openbravo-POS-iPhone-App, under directory /UnicentaPOS/src-pos/com/openbravo/pos/payment/.

Source file: PaymentGatewayPayPoint.java

  19 
vote

/** 
 * Creates a new instance of PaymentGatewaySECPay 
 */
public PaymentGatewayPayPoint(AppProperties props){
  System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
  Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  m_sCommerceID=props.getProperty("payment.commerceid");
  AltEncrypter cypher=new AltEncrypter("cypherkey" + props.getProperty("payment.commerceid"));
  this.m_sCommercePassword=cypher.decrypt(props.getProperty("payment.commercepassword").substring(6));
  m_bTestMode=Boolean.valueOf(props.getProperty("payment.testmode")).booleanValue();
  m_sCurrency=(Locale.getDefault().getCountry().isEmpty()) ? Currency.getInstance("EUR").getCurrencyCode() : Currency.getInstance(Locale.getDefault()).getCurrencyCode();
}
 

Example 22

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/httpclient/.

Source file: AbstractCertificateRepository.java

  19 
vote

public int initPKCS11(String name,String library,int slotListIndex,String kspassword){
  try {
    if (!isProviderAvailable("PKCS11")) {
      return -1;
    }
    StringBuffer cardConfig=new StringBuffer();
    cardConfig.append("name = ").append(name).append("\n");
    cardConfig.append("library = ").append(library).append("\n");
    cardConfig.append("slotListIndex = ").append(Integer.toString(slotListIndex)).append("\n");
    InputStream is=new ByteArrayInputStream(cardConfig.toString().getBytes());
    Class pkcs11Class=Class.forName("sun.security.pkcs11.SunPKCS11");
    Constructor c=pkcs11Class.getConstructor(new Class[]{InputStream.class});
    Provider pkcs11=(Provider)c.newInstance(new Object[]{is});
    Security.addProvider(pkcs11);
    KeyStore ks=KeyStore.getInstance("PKCS11");
    ks.load(null,kspassword == null ? null : kspassword.toCharArray());
    return addKeyStore(ks,name);
  }
 catch (  Exception e) {
    System.err.println("Error instantiating the PKCS11 provider");
    e.printStackTrace();
    return -1;
  }
}
 

Example 23

From project PDF-to-unusual-HTML, under directory /PDF-to-unusual-HTML/src/org/apache/pdfbox/pdmodel/encryption/.

Source file: SecurityHandlersManager.java

  19 
vote

/** 
 * Get the singleton instance.
 * @return The SecurityHandlersManager.
 */
public static SecurityHandlersManager getInstance(){
  if (instance == null) {
    instance=new SecurityHandlersManager();
  }
  Security.addProvider(new BouncyCastleProvider());
  return instance;
}
 

Example 24

From project picketbox-keystore, under directory /src/main/java/org/picketbox/keystore/util/.

Source file: SecurityActions.java

  19 
vote

static void addProvider(final Provider provider){
  if (System.getSecurityManager() == null) {
    Security.addProvider(provider);
  }
 else {
    AccessController.doPrivileged(new PrivilegedAction<Void>(){
      @Override public Void run(){
        Security.addProvider(provider);
        return null;
      }
    }
);
  }
}
 

Example 25

From project PIE, under directory /R2/pie-runtime/src/main/java/com/pieframework/runtime/utils/.

Source file: CertificateUtils.java

  19 
vote

public static String encryptPassword(String rdpPassword,X509Certificate certificate){
  Security.addProvider(new BouncyCastleProvider());
  String encryptedPassword="";
  try {
    certificate.checkValidity();
    CMSEnvelopedDataGenerator envDataGen=new CMSEnvelopedDataGenerator();
    envDataGen.addKeyTransRecipient(certificate);
    CMSProcessable envData=new CMSProcessableByteArray(rdpPassword.getBytes());
    CMSEnvelopedData enveloped=envDataGen.generate(envData,CMSEnvelopedDataGenerator.DES_EDE3_CBC,"BC");
    byte[] data=enveloped.getEncoded();
    encryptedPassword=new String(Base64.encodeBase64(data));
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return encryptedPassword;
}
 

Example 26

From project platform_1, under directory /trial/component/src/main/java/org/exoplatform/trial/.

Source file: Utils.java

  19 
vote

public static String getModifiedMD5Code(byte[] dataToHash){
  Security.addProvider(new BouncyCastleProvider());
  Provider provBC=Security.getProvider("BC");
  MessageDigest digest=null;
  try {
    digest=MessageDigest.getInstance("MD5",provBC);
  }
 catch (  NoSuchAlgorithmException exception) {
    throw new RuntimeException(exception);
  }
  digest.update(dataToHash);
  byte[] hashMD5=digest.digest(dataToHash);
  StringBuffer hashMD5String=new StringBuffer();
  for (int i=0; i < hashMD5.length; i++) {
    hashMD5[i]%=26;
    hashMD5[i]=(byte)Math.abs(hashMD5[i]);
    hashMD5[i]+=((byte)'A' - 1);
    hashMD5String.append(((char)hashMD5[i]));
  }
  return hashMD5String.toString();
}
 

Example 27

From project pos_1, under directory /src-pos/com/openbravo/pos/payment/.

Source file: PaymentGatewayPayPoint.java

  19 
vote

/** 
 * Creates a new instance of PaymentGatewaySECPay 
 */
public PaymentGatewayPayPoint(AppProperties props){
  System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
  Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  m_sCommerceID=props.getProperty("payment.commerceid");
  AltEncrypter cypher=new AltEncrypter("cypherkey" + props.getProperty("payment.commerceid"));
  this.m_sCommercePassword=cypher.decrypt(props.getProperty("payment.commercepassword").substring(6));
  m_bTestMode=Boolean.valueOf(props.getProperty("payment.testmode")).booleanValue();
  m_sCurrency=(Locale.getDefault().getCountry().isEmpty()) ? Currency.getInstance("EUR").getCurrencyCode() : Currency.getInstance(Locale.getDefault()).getCurrencyCode();
}
 

Example 28

From project qi4j-libraries, under directory /shiro-core/src/main/java/org/qi4j/library/shiro/bootstrap/.

Source file: ShiroLifecycleService.java

  19 
vote

public void activate() throws Exception {
  if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
    Security.addProvider(new BouncyCastleProvider());
  }
  obf.newObject(RealmActivator.class).activateRealm();
}
 

Example 29

From project red5-mavenized, under directory /red5_base/src/test/java/org/red5/server/crypto/.

Source file: HMACTest.java

  19 
vote

@Test public void testHMAC(){
  HMAC h1=new HMAC();
  assertNotNull(h1);
  try {
    Provider sp=new com.sun.crypto.provider.SunJCE();
    Security.addProvider(sp);
  }
 catch (  Exception e) {
    fail("Problem loading crypto provider" + e);
  }
  byte[] hmac=h1.computeMac();
  assertNull("Currently HMAC is broken since you can't actually " + "set the keyData or data elements.  This test will break once someone fixes that",hmac);
}
 

Example 30

From project scape, under directory /scape-core/src/main/java/eu/scape_project/core/utils/.

Source file: DigestUtilities.java

  19 
vote

/** 
 * @return the string names of the Message Digest algorithms supported by java
 */
public static Set<String> getMessageDigestAlgorithmNames(){
  Set<String> algNames=new HashSet<String>();
  for (  Provider prov : Security.getProviders()) {
    Set<Object> keys=prov.keySet();
    for (    Object objKeyPair : keys) {
      String strKeyPair=(String)objKeyPair;
      String key=strKeyPair.split(" ")[0];
      if (key.startsWith(JAVA_SECURITY_ALG_ALIAS_PREFIX)) {
        key=key.substring(JAVA_SECURITY_ALG_ALIAS_PREFIX.length());
      }
      if (key.startsWith(JAVA_SECURITY_DIGEST_PREFIX)) {
        algNames.add(key.substring(JAVA_SECURITY_DIGEST_PREFIX.length() + 1));
      }
    }
  }
  return algNames;
}
 

Example 31

From project security, under directory /external/src/main/java/org/jboss/seam/security/external/saml/.

Source file: SamlSignatureUtilForPostBinding.java

  19 
vote

private XMLSignatureFactory getXMLSignatureFactory(){
  if (Security.getProvider("DOM") != null) {
    return XMLSignatureFactory.getInstance("DOM");
  }
 else {
    return XMLSignatureFactory.getInstance("DOM",new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
  }
}
 

Example 32

From project sisu-goodies, under directory /crypto/src/main/java/org/sonatype/sisu/goodies/crypto/internal/.

Source file: CryptoHelperImpl.java

  19 
vote

/** 
 * Configures the  {@link BouncyCastleProvider} if its has not already been added.
 * @return The {@link BouncyCastleProvider} instance.
 * @since 1.5
 */
public static Provider configureProvider(){
  Provider provider=Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
  if (provider == null) {
    provider=new BouncyCastleProvider();
    Security.addProvider(provider);
  }
  return provider;
}
 

Example 33

From project SPDX-Tools, under directory /lib-source/grddl-src/com/hp/hpl/jena/grddl/impl/.

Source file: SecManager.java

  19 
vote

private boolean isJenaAnonId(Class[] classContext){
  int anonId=-1;
  for (int i=0; i < classContext.length; i++)   if (classContext[i] == AnonId.class) {
    anonId=i;
    break;
  }
  if (anonId == -1)   return false;
  dumpClassContext();
  if (true)   return true;
  for (int i=0; i < anonId; i++) {
    Class c=classContext[i];
    if (c == SecManager.class)     continue;
    if (c == UID.class)     continue;
    if (c == Security.class)     continue;
    if (c == SecureRandom.class)     continue;
    if (c.getName().startsWith("sun.security.jca.Provider"))     continue;
    return false;
  }
  return true;
}
 

Example 34

From project spring-security, under directory /core/src/main/java/org/springframework/security/authentication/jaas/.

Source file: JaasAuthenticationProvider.java

  19 
vote

/** 
 * Loops through the login.config.url.1,login.config.url.2 properties looking for the login configuration. If it is not set, it will be set to the last available login.config.url.X property.
 */
private void configureJaasUsingLoop() throws IOException {
  String loginConfigUrl=convertLoginConfigToUrl();
  boolean alreadySet=false;
  int n=1;
  final String prefix="login.config.url.";
  String existing;
  while ((existing=Security.getProperty(prefix + n)) != null) {
    alreadySet=existing.equals(loginConfigUrl);
    if (alreadySet) {
      break;
    }
    n++;
  }
  if (!alreadySet) {
    String key=prefix + n;
    log.debug("Setting security property [" + key + "] to: "+ loginConfigUrl);
    Security.setProperty(key,loginConfigUrl);
  }
}
 

Example 35

From project thumbslug, under directory /src/main/java/org/candlepin/thumbslug/ssl/.

Source file: SslContextFactory.java

  19 
vote

public static SSLContext getServerContext(String keystoreUrl,String keystorePassword) throws SslKeystoreException {
  if (serverContext != null) {
    return serverContext;
  }
  String algorithm=Security.getProperty("ssl.KeyManagerFactory.algorithm");
  if (algorithm == null) {
    algorithm="SunX509";
  }
  FileInputStream fis=null;
  try {
    log.info("reading keystore");
    fis=new FileInputStream(new File(keystoreUrl));
    KeyStore ks=KeyStore.getInstance("PKCS12");
    ks.load(fis,keystorePassword.toCharArray());
    KeyManagerFactory kmf=KeyManagerFactory.getInstance(algorithm);
    kmf.init(ks,keystorePassword.toCharArray());
    serverContext=SSLContext.getInstance(PROTOCOL);
    serverContext.init(kmf.getKeyManagers(),ServerContextTrustManagerFactory.getTrustManagers(),null);
  }
 catch (  Exception e) {
    throw new SslKeystoreException("Failed to initialize the server-side SSLContext.",e);
  }
 finally {
    if (fis != null) {
      try {
        fis.close();
      }
 catch (      IOException e) {
        throw new Error("Failed to initialize the client-side SSLContext",e);
      }
    }
  }
  return serverContext;
}
 

Example 36

From project tinfoil-sms, under directory /branches/crypto-dev/strippedcastle/src/org/spongycastle/jce/.

Source file: ECKeyUtil.java

  19 
vote

/** 
 * Convert a passed in public EC key to have explicit parameters. If the key is already using explicit parameters it is returned.
 * @param key key to be converted
 * @param providerName provider name to be used.
 * @return the equivalent key with explicit curve parameters
 * @throws IllegalArgumentException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public static PublicKey publicToExplicitParameters(PublicKey key,String providerName) throws IllegalArgumentException, NoSuchAlgorithmException, NoSuchProviderException {
  Provider provider=Security.getProvider(providerName);
  if (provider == null) {
    throw new NoSuchProviderException("cannot find provider: " + providerName);
  }
  return publicToExplicitParameters(key,provider);
}
 

Example 37

From project twitstreet, under directory /src/com/twitstreet/mail/.

Source file: MailMgrImpl.java

  19 
vote

@Override public void sendMail(String subject,String message) throws MessagingException {
  boolean debug=false;
  Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  Properties props=new Properties();
  props.put("mail.smtp.host",SMTP_HOST_NAME);
  props.put("mail.smtp.auth","true");
  props.put("mail.debug","true");
  props.put("mail.smtp.port",SMTP_PORT);
  props.put("mail.smtp.socketFactory.port",SMTP_PORT);
  props.put("mail.smtp.socketFactory.class",SSL_FACTORY);
  props.put("mail.smtp.socketFactory.fallback","false");
  Session session=Session.getDefaultInstance(props,new javax.mail.Authenticator(){
    protected PasswordAuthentication getPasswordAuthentication(){
      return new PasswordAuthentication(configMgr.getMailDealer(),configMgr.getMailDealerPassword());
    }
  }
);
  session.setDebug(debug);
  Message msg=new MimeMessage(session);
  msg.setFrom();
  String[] recipients=configMgr.getMailRecipients();
  InternetAddress[] addressTo=new InternetAddress[recipients.length];
  for (int i=0; i < recipients.length; i++) {
    addressTo[i]=new InternetAddress(recipients[i]);
  }
  msg.setRecipients(Message.RecipientType.TO,addressTo);
  msg.setSubject(subject);
  msg.setContent(message,"text/plain;charset=UTF-8");
  Transport.send(msg);
}
 

Example 38

From project Utah-Tools-Decision-Support, under directory /core/edu.utah.cdmcc.encryption/org/jasypt/registry/.

Source file: AlgorithmRegistry.java

  19 
vote

/** 
 * <p> Returns a set with the names of all the registered PBE (Password-Based Encryption) algorithms. This set will also include algorithms from any third-party (non-JVM) registered providers. </p>
 * @since 1.7
 * @return a Set of Strings with the names of all the registeredPBE algorithms.
 */
public static Set getAllPBEAlgorithms(){
  final List algos=new ArrayList(Security.getAlgorithms("Cipher"));
  Collections.sort(algos);
  final LinkedHashSet pbeAlgos=new LinkedHashSet();
  final Iterator algosIter=algos.iterator();
  while (algosIter.hasNext()) {
    final String algo=(String)algosIter.next();
    if (algo != null && algo.startsWith("PBE")) {
      pbeAlgos.add(algo);
    }
  }
  return Collections.unmodifiableSet(pbeAlgos);
}
 

Example 39

From project voms-api-java, under directory /src/main/java/org/glite/voms/contact/.

Source file: VOMSSocket.java

  19 
vote

protected SSLSocketFactory getFactory() throws IOException, GeneralSecurityException {
  SSLSocketFactory socketFactory=null;
  if (Security.getProvider("BC") == null) {
    Security.addProvider(new BouncyCastleProvider());
  }
  log.debug("Creating socket Factory");
  try {
    context=SSLContext.getInstance("SSLv3");
    log.debug("CONTEXT CREATED: " + context.getProtocol());
    log.debug("Context: " + context);
    context.init(new VOMSKeyManager[]{new VOMSKeyManager(cred)},new VOMSTrustManager[]{new VOMSTrustManager("")},SecureRandom.getInstance("SHA1PRNG"));
    return context.getSocketFactory();
  }
 catch (  SSLException e) {
    log.fatal("Error opening SSL socket: " + e.getMessage());
    if (log.isDebugEnabled())     log.debug(e.getMessage(),e);
    throw e;
  }
catch (  IOException e) {
    log.fatal("Error opening SSL socket: " + e.getMessage());
    if (log.isDebugEnabled())     log.debug(e.getMessage(),e);
    throw e;
  }
}
 

Example 40

From project xnio_1, under directory /api/src/main/java/org/xnio/sasl/.

Source file: SaslUtils.java

  19 
vote

private static <T>Iterator<T> getFactories(Class<T> type,ClassLoader classLoader,boolean includeGlobal){
  Set<T> factories=new LinkedHashSet<T>();
  final ServiceLoader<T> loader=ServiceLoader.load(type,classLoader);
  for (  T factory : loader) {
    factories.add(factory);
  }
  if (includeGlobal) {
    Set<String> loadedClasses=new HashSet<String>();
    final String filter=type.getSimpleName() + ".";
    Provider[] providers=Security.getProviders();
    for (    Provider currentProvider : providers) {
      final ClassLoader cl=currentProvider.getClass().getClassLoader();
      for (      Object currentKey : currentProvider.keySet()) {
        if (currentKey instanceof String && ((String)currentKey).startsWith(filter) && ((String)currentKey).indexOf(' ') < 0) {
          String className=currentProvider.getProperty((String)currentKey);
          if (className != null && loadedClasses.add(className)) {
            try {
              factories.add(Class.forName(className,true,cl).asSubclass(type).newInstance());
            }
 catch (            ClassNotFoundException e) {
            }
catch (            ClassCastException e) {
            }
catch (            InstantiationException e) {
            }
catch (            IllegalAccessException e) {
            }
          }
        }
      }
    }
  }
  return factories.iterator();
}