Java Code Examples for java.security.Provider

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 picketbox-keystore, under directory /src/test/java/org/picketbox/test/keystore/.

Source file: PicketBoxDBKeyStoreTestCase.java

  19 
vote

/** 
 * Ensure we check against Null KeyStore Password
 * @throws Exception
 */
@Test(expected=IllegalArgumentException.class) public void testNullKeyStorePassword() throws Exception {
  Provider provider=new PicketBoxKeyStoreDBProvider("PicketBox/Keystore",1.0,"KeyStore by PicketBox");
  KeyStore keystore=KeyStore.getInstance(KeyStore.getDefaultType(),provider);
  assertNotNull(keystore);
  keystore.load(null,null);
}
 

Example 2

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 3

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

Source file: CryptoHelperImpl.java

  18 
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 4

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

Source file: ECKeyUtil.java

  18 
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 5

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

Source file: KeyStoreComponent.java

  17 
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 6

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

Source file: DNIe.java

  17 
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 7

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

Source file: AbstractCertificateRepository.java

  17 
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 8

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

Source file: Utils.java

  17 
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 9

From project Tanks_1, under directory /src/org/apache/mina/filter/ssl/.

Source file: BogusTrustManagerFactory.java

  17 
vote

public BogusTrustManagerFactory(){
  super(new BogusTrustManagerFactorySpi(),new Provider("MinaBogus",1.0,""){
    private static final long serialVersionUID=-4024169055312053827L;
  }
,"MinaBogus");
}
 

Example 10

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

Source file: Crypto.java

  15 
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 11

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

Source file: Sasl.java

  15 
vote

private static Object newInstance(String factoryName,Provider prv) throws SaslException {
  String msg="auth.31";
  Object factory;
  ClassLoader cl=prv.getClass().getClassLoader();
  if (cl == null) {
    cl=ClassLoader.getSystemClassLoader();
  }
  try {
    factory=(Class.forName(factoryName,true,cl)).newInstance();
    return factory;
  }
 catch (  IllegalAccessException e) {
    throw new SaslException(msg + factoryName,e);
  }
catch (  ClassNotFoundException e) {
    throw new SaslException(msg + factoryName,e);
  }
catch (  InstantiationException e) {
    throw new SaslException(msg + factoryName,e);
  }
}
 

Example 12

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

Source file: Sasl.java

  15 
vote

private static Object newInstance(String factoryName,Provider prv) throws SaslException {
  String msg="auth.31";
  Object factory;
  ClassLoader cl=prv.getClass().getClassLoader();
  if (cl == null) {
    cl=ClassLoader.getSystemClassLoader();
  }
  try {
    factory=(Class.forName(factoryName,true,cl)).newInstance();
    return factory;
  }
 catch (  IllegalAccessException e) {
    throw new SaslException(msg + factoryName,e);
  }
catch (  ClassNotFoundException e) {
    throw new SaslException(msg + factoryName,e);
  }
catch (  InstantiationException e) {
    throw new SaslException(msg + factoryName,e);
  }
}
 

Example 13

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/util/.

Source file: SamlUtils.java

  15 
vote

private static Element signSamlElement(Element element,PrivateKey privKey,PublicKey pubKey){
  try {
    final String providerName=System.getProperty("jsr105Provider",JSR_105_PROVIDER);
    final XMLSignatureFactory sigFactory=XMLSignatureFactory.getInstance("DOM",(Provider)Class.forName(providerName).newInstance());
    final List envelopedTransform=Collections.singletonList(sigFactory.newTransform(Transform.ENVELOPED,(TransformParameterSpec)null));
    final Reference ref=sigFactory.newReference("",sigFactory.newDigestMethod(DigestMethod.SHA1,null),envelopedTransform,null,null);
    SignatureMethod signatureMethod;
    if (pubKey instanceof DSAPublicKey) {
      signatureMethod=sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1,null);
    }
 else     if (pubKey instanceof RSAPublicKey) {
      signatureMethod=sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1,null);
    }
 else {
      throw new RuntimeException("Error signing SAML element: Unsupported type of key");
    }
    final CanonicalizationMethod canonicalizationMethod=sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,(C14NMethodParameterSpec)null);
    final SignedInfo signedInfo=sigFactory.newSignedInfo(canonicalizationMethod,signatureMethod,Collections.singletonList(ref));
    final KeyInfoFactory keyInfoFactory=sigFactory.getKeyInfoFactory();
    final KeyValue keyValuePair=keyInfoFactory.newKeyValue(pubKey);
    final KeyInfo keyInfo=keyInfoFactory.newKeyInfo(Collections.singletonList(keyValuePair));
    org.w3c.dom.Element w3cElement=toDom(element);
    DOMSignContext dsc=new DOMSignContext(privKey,w3cElement);
    org.w3c.dom.Node xmlSigInsertionPoint=getXmlSignatureInsertLocation(w3cElement);
    dsc.setNextSibling(xmlSigInsertionPoint);
    XMLSignature signature=sigFactory.newXMLSignature(signedInfo,keyInfo);
    signature.sign(dsc);
    return toJdom(w3cElement);
  }
 catch (  final Exception e) {
    throw new RuntimeException("Error signing SAML element: " + e.getMessage(),e);
  }
}
 

Example 14

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

Source file: KeyStoreGenerator.java

  15 
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 15

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

Source file: CertificateUtil.java

  15 
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 16

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

Source file: JCEHandler.java

  15 
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 17

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

Source file: Main.java

  15 
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 18

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

Source file: EncryptionModule.java

  15 
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 19

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

Source file: DigestUtilities.java

  15 
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 20

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

Source file: SimpleDigesterConfig.java

  15 
vote

/** 
 * <p> Sets the class name for the security provider to be used for  obtaining the digest algorithm. This method is an alternative to  both  {@link #setProviderName(String)} {@link #setProvider(Provider)} and they should not be used altogether. The provider specified with  {@link #setProviderClassName(String)} does nothave to be registered beforehand, and its use will not result in its being registered. </p> <p> If both the <tt>providerName</tt> and <tt>provider</tt> properties are set, only <tt>provider</tt> will be used, and <tt>providerName</tt> will have no meaning for the digester object. </p> <p> If not set, null will be returned. </p> <p> Determines the result of:  {@link #getProvider()}</p>
 * @since 1.4
 * @param providerClassName the name of the security provider class.
 */
public void setProviderClassName(final String providerClassName){
  if (providerClassName != null) {
    try {
      final Class providerClass=Thread.currentThread().getContextClassLoader().loadClass(providerClassName);
      this.provider=(Provider)providerClass.newInstance();
    }
 catch (    Exception e) {
      throw new EncryptionInitializationException(e);
    }
  }
 else {
    this.provider=null;
  }
}
 

Example 21

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

Source file: FileCertReader.java

  15 
vote

/** 
 * Creates a new instance of CertReader with the specified provider.
 * @param provider   the provider to be used in creating thecertificates etc.
 */
public FileCertReader(Provider provider) throws CertificateException {
  try {
    certFactory=CertificateFactory.getInstance("X.509",provider);
  }
 catch (  Exception e) {
    logger.error("Error while creating a FileCertReader: " + e.getMessage());
    throw new CertificateException("Error while creating a FileCertReader: " + e.getMessage(),e);
  }
}
 

Example 22

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

Source file: SaslUtils.java

  15 
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();
}