private void installSecureRandomProvider(Provider provider) { Provider[] providers = Security.getProviders("SecureRandom.SHA1PRNG"); if (providers == null || providers.length == 0 || !provider.getClass().equals(providers[0].getClass())) { Security.insertProviderAt(provider, 1); } // Check the new provider is the default when no algorithm is specified SecureRandom random = new SecureRandom(); if (!provider.getClass().equals(random.getProvider().getClass())) { throw new SecurityException("Wrong SecureRandom provider: " + random.getProvider().getClass()); } // Check the new provider is the default when SHA1PRNG is specified try { random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new SecurityException(e); } if (!provider.getClass().equals(random.getProvider().getClass())) { throw new SecurityException("Wrong SHA1PRNG provider: " + random.getProvider().getClass()); } }
public static void main(String[] args) throws Exception { Provider provider = Security.getProvider("SunJCE"); if (provider == null) { throw new RuntimeException("SunJCE provider not exist"); } // generate no-padding cipher with secret key Cipher c = Cipher.getInstance("DES/CBC/NoPadding", provider); KeyGenerator kgen = KeyGenerator.getInstance("DES", provider); SecretKey skey = kgen.generateKey(); // this is the improperly padded plaintext c.init(Cipher.ENCRYPT_MODE, skey); // encrypt plaintext byte[] cipher = c.doFinal(PLAIN_TEXT); AlgorithmParameters params = c.getParameters(); // generate cipher that enforces PKCS5 padding c = Cipher.getInstance("DES/CBC/PKCS5Padding", provider); c.init(Cipher.DECRYPT_MODE, skey, params); try { c.doFinal(cipher); throw new RuntimeException( "ERROR: Expected BadPaddingException not thrown"); } catch (BadPaddingException expected) { out.println("Expected BadPaddingException thrown"); } }
/** * Pair a private key with a public EC point. * * All private key operations will use the provider. */ public ECKey(Provider provider, @Nullable PrivateKey privKey, ECPoint pub) { this.provider = provider; if (privKey == null || isECPrivateKey(privKey)) { this.privKey = privKey; } else { throw new IllegalArgumentException( "Expected EC private key, given a private key object with class " + privKey.getClass().toString() + " and algorithm " + privKey.getAlgorithm()); } if (pub == null) { throw new IllegalArgumentException("Public key may not be null"); } else { this.pub = pub; } }
public static void main(String[] args) throws Exception { Provider myProvider = new MyProvider(); Security.addProvider(myProvider); System.out.println(Arrays.asList(Security.getProviders())); TerminalFactory.getInstance("MyType", new Object()).terminals(); if (!callMethod) { throw new RuntimeException("Expected engineTerminals() not called"); } }
public static void main(String[] args) { PBESealedObject test = new PBESealedObject(); Provider sunjce = Security.getProvider("SunJCE"); if (!test.runAll(sunjce, System.out)) { throw new RuntimeException("One or more tests have failed...."); } }
/** * Verifies that this CRL was signed using the * private key that corresponds to the given public key, * and that the signature verification was computed by * the given provider. Note that the specified Provider object * does not have to be registered in the provider list. * * @param key the PublicKey used to carry out the verification. * @param sigProvider the signature provider. * * @exception NoSuchAlgorithmException on unsupported signature * algorithms. * @exception InvalidKeyException on incorrect key. * @exception SignatureException on signature errors. * @exception CRLException on encoding errors. */ public synchronized void verify(PublicKey key, Provider sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { if (signedCRL == null) { throw new CRLException("Uninitialized CRL"); } Signature sigVerf = null; if (sigProvider == null) { sigVerf = Signature.getInstance(sigAlgId.getName()); } else { sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider); } sigVerf.initVerify(key); if (tbsCertList == null) { throw new CRLException("Uninitialized CRL"); } sigVerf.update(tbsCertList, 0, tbsCertList.length); if (!sigVerf.verify(signature)) { throw new SignatureException("Signature does not match."); } verifiedPublicKey = key; }
/** * Build the CertStore from the current inputs. * * @return a CertStore. * @throws GeneralSecurityException */ public CertStore build() throws GeneralSecurityException { CollectionCertStoreParameters params = convertHolders(certificateConverter, crlConverter); if (provider instanceof String) { return CertStore.getInstance(type, params, (String)provider); } if (provider instanceof Provider) { return CertStore.getInstance(type, params, (Provider)provider); } return CertStore.getInstance(type, params); }
@Override public void main(Provider p) throws Exception { SecureRandom random; try { random = SecureRandom.getInstance("PKCS11"); } catch (NoSuchAlgorithmException e) { System.out.println("Provider " + p + " does not support SecureRandom, skipping"); e.printStackTrace(); return; } byte[] b = new byte[32]; random.nextBytes(b); System.out.println(toString(b)); random.setSeed(b); random.nextBytes(b); System.out.println(toString(b)); System.out.println("OK"); }
@Override public void main(Provider p) { List<String> algorithms = getSupportedAlgorithms("Mac", "Hmac", p); boolean success = true; for (String alg : algorithms) { try { doTest(alg, p); } catch (Exception e) { System.out.println("Unexpected exception: " + e); e.printStackTrace(); success = false; } } if (!success) { throw new RuntimeException("Test failed"); } }
@BeforeClass public static void testProviderInstallationAtRuntime() { /* install wolfJCE provider at runtime */ Security.addProvider(new WolfCryptProvider()); Provider p = Security.getProvider("wolfJCE"); assertNotNull(p); /* build list of enabled curves and key sizes, * getCurveSizeFromName() will return 0 if curve not found */ Ecc tmp = new Ecc(); for (int i = 0; i < supportedCurves.length; i++) { int size = tmp.getCurveSizeFromName( supportedCurves[i].toUpperCase()); if (size > 0) { enabledCurves.add(supportedCurves[i]); if (!enabledKeySizes.contains(new Integer(size))) { enabledKeySizes.add(new Integer(size)); } } } }
private static void testKeyAgreement(KeyPair kpA, KeyPair kpB, Provider p) throws Exception { KeyAgreement ka1 = KeyAgreement.getInstance("ECDH", p); ka1.init(kpA.getPrivate()); ka1.doPhase(kpB.getPublic(), true); byte[] s1 = ka1.generateSecret(); KeyAgreement ka2 = KeyAgreement.getInstance("ECDH", p); ka2.init(kpB.getPrivate()); ka2.doPhase(kpA.getPublic(), true); byte[] s2 = ka2.generateSecret(); if (Arrays.equals(s1, s2) == false) { System.out.println("expected: " + toString(s1)); System.out.println("actual: " + toString(s2)); throw new Exception("Generated secrets do not match"); } }
static byte[] crypt( boolean encrypt, String provider, byte[] bytes, char[] password, String dekAlgName, byte[] iv) throws IOException { Provider prov = null; if (provider != null) { prov = Security.getProvider(provider); if (prov == null) { throw new EncryptionException("cannot find provider: " + provider); } } return crypt(encrypt, prov, bytes, password, dekAlgName, iv); }
private static void testSigning(Provider p, String algorithm, byte[] data, KeyPair kp1, KeyPair kp2) throws Exception { System.out.print(" " + algorithm); Signature s = Signature.getInstance(algorithm, p); s.initSign(kp1.getPrivate()); s.update(data); byte[] sig = s.sign(); s = Signature.getInstance(algorithm, p); s.initVerify(kp1.getPublic()); s.update(data); boolean r = s.verify(sig); if (r == false) { throw new Exception("Signature did not verify"); } s.initVerify(kp2.getPublic()); s.update(data); r = s.verify(sig); if (r) { throw new Exception("Signature should not verify"); } }
/** * Helper routine to go through all properties contined in a * provider and add its mechanisms to the list of supported * mechanisms. If no default mechanism has been assinged so far, * it sets the default MechanismFactory and Oid as well. * @param p the provider to query * @return true if there is at least one mechanism that this * provider contributed, false otherwise */ private boolean addAllMechsFromProvider(Provider p) { String prop; boolean retVal = false; // Get all props for this provider Enumeration<Object> props = p.keys(); // See if there are any GSS prop's while (props.hasMoreElements()) { prop = (String) props.nextElement(); if (isMechFactoryProperty(prop)) { // Ok! This is a GSS provider! try { Oid mechOid = getOidFromMechFactoryProperty(prop); mechs.add(mechOid); retVal = true; } catch (GSSException e) { // Skip to next property GSSUtil.debug("Ignore the invalid property " + prop + " from provider " + p.getName()); } } // Processed GSS property } // while loop return retVal; }
public AbstractXMLRSSTest(String algorithm, Provider provider, KeyPair keyPair) { Security.insertProviderAt(provider, 1); this.algorithm = algorithm; this.providerName = provider.getName(); this.provider = provider; AbstractXMLRSSTest.keyPair = keyPair; }
/** * @return a non-null content crypto material. */ static ContentCryptoMaterial fromInstructionFile( Map<String, String> instFile, EncryptionMaterialsAccessor kekMaterialAccessor, Provider securityProvider, boolean keyWrapExpected, AWSKMS kms) { return fromInstructionFile0(instFile, kekMaterialAccessor, securityProvider, null, NONE, keyWrapExpected, kms); }
public static KeyAgreement getInstance(final Provider provider) { try { return KeyAgreement.getInstance(ALGORITHM, provider); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(algorithmAssertionMsg, ex); } }
private static boolean hasProvider( Class providerClass ) { Provider[] list = Security.getProviders(); for (int i = 0; i < list.length; i++) { if (list[i].getClass().equals( providerClass )) return true; } return false; }
public static Signature getRawInstance(final Provider provider) { try { return Signature.getInstance(RAW_ALGORITHM, provider); } catch (NoSuchAlgorithmException ex) { throw new AssertionError(rawAlgorithmAssertionMsg, ex); } }
static EnvelopedDataHelper createContentHelper(Provider provider) { if (provider != null) { return new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); } else { return new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); } }
/** * @param materials a non-null encryption material */ private ContentCryptoMaterial buildContentCryptoMaterial( EncryptionMaterials materials, Provider provider, AmazonWebServiceRequest req) { // Randomly generate the IV final byte[] iv = new byte[contentCryptoScheme.getIVLengthInBytes()]; cryptoScheme.getSecureRandom().nextBytes(iv); if (materials.isKMSEnabled()) { final Map<String, String> encryptionContext = ContentCryptoMaterial.mergeMaterialDescriptions(materials, req); GenerateDataKeyRequest keyGenReq = new GenerateDataKeyRequest() .withEncryptionContext(encryptionContext) .withKeyId(materials.getCustomerMasterKeyId()) .withKeySpec(contentCryptoScheme.getKeySpec()); keyGenReq .withGeneralProgressListener(req.getGeneralProgressListener()) .withRequestMetricCollector(req.getRequestMetricCollector()) ; GenerateDataKeyResult keyGenRes = kms.generateDataKey(keyGenReq); final SecretKey cek = new SecretKeySpec(copyAllBytesFrom(keyGenRes.getPlaintext()), contentCryptoScheme.getKeyGeneratorAlgorithm()); byte[] keyBlob = copyAllBytesFrom(keyGenRes.getCiphertextBlob()); return ContentCryptoMaterial.wrap(cek, iv, contentCryptoScheme, provider, new KMSSecuredCEK(keyBlob, encryptionContext)); } else { // Generate a one-time use symmetric key and initialize a cipher to encrypt object data return ContentCryptoMaterial.create( generateCEK(materials, provider), iv, materials, cryptoScheme, provider, kms, req); } }
/** * Set the provider to use from a Provider object. * * @param provider the provider to use. * @return the converter instance. */ public JcaX509CertificateConverter setProvider(Provider provider) { this.helper = new ProviderCertHelper(provider); return this; }
public static KeyFactory getInstance(final Provider provider) { try { return KeyFactory.getInstance(ALGORITHM, provider); } catch (NoSuchAlgorithmException ex) { throw new AssertionError(algorithmAssertionMsg, ex); } }
/** * Set the provider to use from a Provider object. * * @param provider the provider to use. * @return the converter instance. */ public JcaX509CRLConverter setProvider(Provider provider) { this.helper = new ProviderCertHelper(provider); return this; }
@Test public void testInteropSignWolfVerify() throws NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, InvalidAlgorithmParameterException { String toSign = "Hello World"; byte[] toSignBuf = toSign.getBytes(); byte[] signature; for (int i = 0; i < wolfJCEAlgos.length; i++) { Signature signer = Signature.getInstance(wolfJCEAlgos[i]); Signature verifier = Signature.getInstance(wolfJCEAlgos[i], "wolfJCE"); assertNotNull(signer); assertNotNull(verifier); Provider prov = signer.getProvider(); if (prov.equals("wolfJCE")) { /* bail out, there isn't another implementation to interop * against by default */ return; } SecureRandom rand = SecureRandom.getInstance("HashDRBG", "wolfJCE"); assertNotNull(rand); /* generate key pair */ KeyPair pair = generateKeyPair(wolfJCEAlgos[i], rand); assertNotNull(pair); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); /* generate signature */ signer.initSign(priv); signer.update(toSignBuf, 0, toSignBuf.length); signature = signer.sign(); /* verify signature */ verifier.initVerify(pub); verifier.update(toSignBuf, 0, toSignBuf.length); boolean verified = verifier.verify(signature); if (verified != true) { fail("Signature verification failed when generating with " + "system default JCE provider and verifying with " + "wolfJCE provider, iteration " + i); } } }
@Override public void main(Provider p) throws Exception { if (p.getService("KeyAgreement", "ECDH") == null) { System.out.println("Provider does not support ECDH, skipping"); return; } if (isNSS(p) && getNSSECC() == ECCState.Basic) { System.out.println("NSS only supports Basic ECC. Skipping.."); return; } /* * PKCS11Test.main will remove this provider if needed */ Providers.setAt(p, 1); if (false) { KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", p); kpg.initialize(163); KeyPair kp = kpg.generateKeyPair(); System.out.println(toString(kp.getPublic().getEncoded())); System.out.println(toString(kp.getPrivate().getEncoded())); kp = kpg.generateKeyPair(); System.out.println(toString(kp.getPublic().getEncoded())); System.out.println(toString(kp.getPrivate().getEncoded())); return; } test(p, pub192a, priv192a, pub192b, priv192b, secret192); test(p, pub163a, priv163a, pub163b, priv163b, secret163); System.out.println("OK"); }
private static Set<Object> getFactories(String serviceName) { HashSet<Object> result = new HashSet<Object>(); if ((serviceName == null) || (serviceName.length() == 0) || (serviceName.endsWith("."))) { return result; } Provider[] providers = Security.getProviders(); HashSet<String> classes = new HashSet<String>(); Object fac; for (int i = 0; i < providers.length; i++) { classes.clear(); // Check the keys for each provider. for (Enumeration<Object> e = providers[i].keys(); e.hasMoreElements(); ) { String currentKey = (String)e.nextElement(); if (currentKey.startsWith(serviceName)) { // We should skip the currentKey if it contains a // whitespace. The reason is: such an entry in the // provider property contains attributes for the // implementation of an algorithm. We are only interested // in entries which lead to the implementation // classes. if (currentKey.indexOf(" ") < 0) { String className = providers[i].getProperty(currentKey); if (!classes.contains(className)) { classes.add(className); try { fac = loadFactory(providers[i], className); if (fac != null) { result.add(fac); } }catch (Exception ignore) { } } } } } } return Collections.unmodifiableSet(result); }
static boolean isBadNSSVersion(Provider p) { if (isNSS(p) && badNSSVersion) { System.out.println("NSS 3.11 has a DER issue that recent " + "version do not."); return true; } return false; }
/** * Instantiate Cipher for the PBE algorithm. * * @param mode Cipher mode: encrypt or decrypt. * @return Cipher in accordance to the PBE algorithm * @throws java.security.GeneralSecurityException */ @Override protected Cipher initCipher(int mode) throws GeneralSecurityException { Provider provider = Security.getProvider("SunJCE"); if (provider == null) { throw new RuntimeException("SunJCE provider does not exist."); } SecretKey key = SecretKeyFactory.getInstance(baseAlgo) .generateSecret(new PBEKeySpec(password.toCharArray())); Cipher ci = Cipher.getInstance(transformation, provider); ci.init(mode, key, new PBEParameterSpec(salt, DEFAULT_ITERATION)); return ci; }
public PBECipherWrapper( Provider p, String algo, String passwd, PrintStream out) throws Exception { super(algo, SecretKeyFactory.getInstance( new StringTokenizer(algo, "/").nextToken(), p).generateSecret( new PBEKeySpec(passwd.toCharArray())), Cipher.getInstance(algo, p), out); int SALT_SIZE = 8; aps = new PBEParameterSpec(generateSalt(SALT_SIZE), ITERATION_COUNT); }
private void init(PrivateKey key, ASN1ObjectIdentifier algorithm, Provider provider) throws NoSuchAlgorithmException { this.key = PrivateKeyInfo.getInstance(key.getEncoded()); this.encryptorBuilder = new JceOpenSSLPKCS8EncryptorBuilder(algorithm); encryptorBuilder.setProvider(provider); }
private void initCiphers(String algo, SecretKey key, AlgorithmParameterSpec aps) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { Provider provider = Security.getProvider("SunJCE"); if (provider == null) { throw new RuntimeException("SunJCE provider does not exist."); } Cipher ci1 = Cipher.getInstance(algo, provider); ci1.init(Cipher.ENCRYPT_MODE, key, aps); pair[0] = ci1; Cipher ci2 = Cipher.getInstance(algo, provider); ci2.init(Cipher.DECRYPT_MODE, key, aps); pair[1] = ci2; }
@Test public void testWolfSignInteropVerify() throws NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, InvalidAlgorithmParameterException { String toSign = "Hello World"; byte[] toSignBuf = toSign.getBytes(); byte[] signature; for (int i = 0; i < wolfJCEAlgos.length; i++) { Signature signer = Signature.getInstance(wolfJCEAlgos[i], "wolfJCE"); Signature verifier = Signature.getInstance(wolfJCEAlgos[i]); assertNotNull(signer); assertNotNull(verifier); Provider prov = verifier.getProvider(); if (prov.equals("wolfJCE")) { /* bail out, there isn't another implementation to interop * against by default */ return; } SecureRandom rand = SecureRandom.getInstance("HashDRBG", "wolfJCE"); assertNotNull(rand); /* generate key pair */ KeyPair pair = generateKeyPair(wolfJCEAlgos[i], rand); assertNotNull(pair); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); /* generate signature */ signer.initSign(priv); signer.update(toSignBuf, 0, toSignBuf.length); signature = signer.sign(); /* verify signature */ verifier.initVerify(pub); verifier.update(toSignBuf, 0, toSignBuf.length); boolean verified = verifier.verify(signature); if (verified != true) { fail("Signature verification failed when generating with " + "wolfJCE and verifying with system default JCE " + "provider"); } } }
/** * return an AlgorithmParameters object representing the parameters to the * key derivation algorithm to the recipient. * * @return AlgorithmParameters object, null if there aren't any. * @deprecated use getKeyDerivationAlgorithm and JceAlgorithmIdentifierConverter(). */ public AlgorithmParameters getKeyDerivationAlgParameters(Provider provider) { try { return new JceAlgorithmIdentifierConverter().setProvider(provider).getAlgorithmParameters(info.getKeyDerivationAlgorithm()); } catch (Exception e) { throw new RuntimeException("exception getting encryption parameters " + e); } }
/** * return a X509Store containing the public key certificates, if any, contained * in this message. * * @param type type of store to create * @param provider provider to use * @return a store of public key certificates * @exception NoSuchStoreException if the store type isn't available. * @exception CMSException if a general exception prevents creation of the X509Store * @deprecated use base Store returning method */ public X509Store getCertificates( String type, Provider provider) throws NoSuchStoreException, CMSException { if (certificateStore == null) { certificateStore = HELPER.createCertificateStore(type, provider, this.getCertificates()); } return certificateStore; }
/** * Helper routine that uses a preferences entry to obtain an * implementation of a MechanismFactory from it. * @param e the preferences entry that contains the provider and * either a null of an explicit oid that matched the oid of the * desired mechanism. * @param mechOid the oid of the desired mechanism * @throws GSSException If the application explicitly requested * this entry's provider to be used for the desired mechanism but * some problem is encountered */ private MechanismFactory getMechFactory(PreferencesEntry e, Oid mechOid) throws GSSException { Provider p = e.getProvider(); /* * See if a MechanismFactory was previously instantiated for * this provider and mechanism combination. */ PreferencesEntry searchEntry = new PreferencesEntry(p, mechOid); MechanismFactory retVal = factories.get(searchEntry); if (retVal == null) { /* * Apparently not. Now try to instantiate this class from * the provider. */ String prop = PROV_PROP_PREFIX + mechOid.toString(); String className = p.getProperty(prop); if (className != null) { retVal = getMechFactoryImpl(p, className, mechOid, caller); factories.put(searchEntry, retVal); } else { /* * This provider does not support this mechanism. * If the application explicitly requested that * this provider be used for this mechanism, then * throw an exception */ if (e.getOid() != null) { throw new GSSExceptionImpl(GSSException.BAD_MECH, "Provider " + p.getName() + " does not support mechanism " + mechOid); } } } return retVal; }
@Before public void setUp() { Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider(); Security.addProvider(provider); preferences = RuntimeEnvironment.application.getSharedPreferences("__leanplum__", Context.MODE_PRIVATE); }