public static void main(String[] args) { try { AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DSA"); paramGen.init(1024); AlgorithmParameters params = paramGen.generateParameters(); DSAParameterSpec dsaParameterSpec = params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(dsaParameterSpec); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); saveKey("BpubKey", publicKey); saveKey("BprivKey", privateKey); } catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidAlgorithmParameterException e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { byte[] iv_1 = { (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x33, (byte) 0x33 }; // check that RC2 is supported by our provider AlgorithmParameters rc2Params = AlgorithmParameters.getInstance("RC2", "SunJCE"); // check that getAlgorithm returns "RC2" if (!rc2Params.getAlgorithm().equals("RC2")) { throw new Exception( "getAlgorithm() returned " + rc2Params.getAlgorithm() + " instead of RC2"); } // test parameters with effective key size and iv byte[] encoded = testParams(rc2Params, new RC2ParameterSpec(2, iv_1)); // test parameters with just iv encoded = testParams(AlgorithmParameters.getInstance("RC2"), new RC2ParameterSpec(0, iv_1)); // test vectors in RFC 2268 runTests(tests); }
public static Message encrypt(PublicKey pubKey, byte[] input) throws CryptoException { Message message = new Message(); message.pubKey = pubKey.getEncoded(); KeyGenerator keyGen; try { keyGen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); try { Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey); message.sessionKey = rsaCipher.doFinal(secretKey.getEncoded()); Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesCipher.init(Cipher.ENCRYPT_MODE, secretKey); AlgorithmParameters params = aesCipher.getParameters(); message.iv = params.getParameterSpec(IvParameterSpec.class).getIV(); message.ciphertext = aesCipher.doFinal(input); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidParameterSpecException e) { throw new CryptoException(e); } return message; }
private DERObject createDERForRecipient(byte[] in, X509Certificate cert) throws IOException, GeneralSecurityException { String s = "1.2.840.113549.3.2"; AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s); AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters(); ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1")); ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream); DERObject derobject = asn1inputstream.readObject(); KeyGenerator keygenerator = KeyGenerator.getInstance(s); keygenerator.init(128); SecretKey secretkey = keygenerator.generateKey(); Cipher cipher = Cipher.getInstance(s); cipher.init(1, secretkey, algorithmparameters); byte[] abyte1 = cipher.doFinal(in); DEROctetString deroctetstring = new DEROctetString(abyte1); KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded()); DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo)); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject); EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring); EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null); ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env); return contentinfo.getDERObject(); }
AlgorithmParameters implGetParameters() { AlgorithmParameters params = null; if (salt == null) { // Cipher is not initialized with parameters; // follow the recommendation in PKCS12 v1.0 // section B.4 to generate salt and iCount. salt = new byte[DEFAULT_SALT_LENGTH]; SunJCE.getRandom().nextBytes(salt); iCount = DEFAULT_COUNT; } PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iCount); try { params = AlgorithmParameters.getInstance(pbeAlgo, "SunJCE"); } catch (GeneralSecurityException gse) { // should never happen throw new RuntimeException("SunJCE provider is not configured properly"); } try { params.init(pbeSpec); } catch (InvalidParameterSpecException ipse) { // should never happen throw new RuntimeException("PBEParameterSpec not supported"); } return params; }
/** * Generate a spec from a curve name * * @return null if fail */ private static ECParameterSpec genSpec(String name) { // convert the ECGenParameterSpecs to ECParameterSpecs for several reasons: // 1) to check availability // 2) efficiency // 3) SigUtil must cast the AlgorithmParameterSpec to a ECParameterSpec // to convert a I2P key to a Java key. Sadly, a ECGenParameterSpec // is not a ECParameterSpec. try { AlgorithmParameters ap; try { ap = AlgorithmParameters.getInstance("EC"); } catch (Exception e) { if (BC_AVAILABLE) { log("Named curve " + name + " is not available, trying BC", e); ap = AlgorithmParameters.getInstance("EC", "BC"); log("Fallback to BC worked for named curve " + name); } else { throw e; } } ECGenParameterSpec ecgps = new ECGenParameterSpec(name); ap.init(ecgps); ECParameterSpec rv = ap.getParameterSpec(ECParameterSpec.class); log("Named curve " + name + " loaded"); return rv; } catch (Exception e) { log("Named curve " + name + " is not available", e); return null; } }
/** {@inheritDoc} */ @Override public byte[] encrypt(final byte[] bytes) throws EncyptionException { try { final javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, this.secretKey); final AlgorithmParameters params = cipher.getParameters(); final byte[] ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV(); final byte[] dataBytes = cipher.doFinal(bytes); final byte[] secret = ArrayOfBytesType.TYPE.toBytes(ivBytes, dataBytes); return secret; } catch (final NoSuchAlgorithmException problem) { throw new EncyptionException(problem); } catch (final NoSuchPaddingException problem) { throw new EncyptionException(problem); } catch (final InvalidKeyException problem) { throw new EncyptionException(problem); } catch (final InvalidParameterSpecException problem) { throw new EncyptionException(problem); } catch (final IllegalBlockSizeException problem) { throw new EncyptionException(problem); } catch (final BadPaddingException problem) { throw new EncyptionException(problem); } }
/** * @tests javax.crypto.Cipher#getParameters() * @tests javax.crypto.Cipher#init(int, java.security.Key, java.security.AlgorithmParameters, * java.security.SecureRandom) */ public void test_getParameters() throws Exception { /* * If this test is changed, implement the following: * test_initILjava_security_KeyLjava_security_AlgorithmParametersLjava_security_SecureRandom() */ SecureRandom sr = new SecureRandom(); Cipher cipher = null; byte[] apEncoding = null; byte[] iv = new byte[8]; sr.nextBytes(iv); AlgorithmParameters ap = AlgorithmParameters.getInstance("DESede"); ap.init(iv, "RAW"); apEncoding = ap.getEncoded("ASN.1"); cipher = Cipher.getInstance(algorithm + "/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap, sr); byte[] cipherParmsEnc = cipher.getParameters().getEncoded("ASN.1"); assertTrue("Parameters differ", Arrays.equals(apEncoding, cipherParmsEnc)); }
protected void engineInit( int paramInt, Key paramKey, AlgorithmParameters paramAlgorithmParameters, SecureRandom paramSecureRandom) { Object localObject2 = null; Object localObject3 = null; if (paramAlgorithmParameters != null) { int i = 0; for (; ; ) { Object localObject1 = localObject3; if (i == this.aXo.length) { break; } try { localObject1 = paramAlgorithmParameters.getParameterSpec(this.aXo[i]); } catch (Exception localException) { i += 1; } } localObject2 = localException; if (localException == null) { throw new InvalidAlgorithmParameterException( "can't handle parameter " + paramAlgorithmParameters.toString()); } } this.aXe = paramAlgorithmParameters; engineInit(paramInt, paramKey, localObject2, paramSecureRandom); }
private void setSignatureParameters(Signature var1, DEREncodable var2) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException { if (var2 != null) { if (!DERNull.INSTANCE.equals(var2)) { String var3 = var1.getAlgorithm(); Provider var4 = var1.getProvider(); AlgorithmParameters var5 = AlgorithmParameters.getInstance(var3, var4); try { byte[] var6 = var2.getDERObject().getDEREncoded(); var5.init(var6); } catch (IOException var17) { StringBuilder var9 = (new StringBuilder()).append("IOException decoding parameters: "); String var10 = var17.getMessage(); String var11 = var9.append(var10).toString(); throw new SignatureException(var11); } if (var1.getAlgorithm().endsWith("MGF1")) { try { AlgorithmParameterSpec var7 = var5.getParameterSpec(PSSParameterSpec.class); var1.setParameter(var7); } catch (GeneralSecurityException var16) { StringBuilder var13 = (new StringBuilder()).append("Exception extracting parameters: "); String var14 = var16.getMessage(); String var15 = var13.append(var14).toString(); throw new SignatureException(var15); } } } } }
/** * Method getAlgParam. * * @return AlgorithmParameters * @param jceName The name of the algorithm parameters which may depend on the provider */ public AlgorithmParameters getAlgParam(String jceName) throws NoSuchAlgorithmException, IOException { if (this.param == null) { return null; } AlgorithmParameters ap = AlgorithmParameters.getInstance(jceName); ap.init(this.param.getValue()); return ap; }
/** * Generates and returns {@link DHParameterSpec}. * * @return {@link String} * @see AlgorithmParameters * @see AlgorithmParameterGenerator */ public static DHParameterSpec generateDiffieHellmanValues() throws NoSuchAlgorithmException, InvalidParameterSpecException { AlgorithmParameterGenerator parameterGenerator = AlgorithmParameterGenerator.getInstance("DH"); parameterGenerator.init(1024); AlgorithmParameters parameters = parameterGenerator.generateParameters(); return (DHParameterSpec) parameters.getParameterSpec(DHParameterSpec.class); }
/** Can be used to generate new parameters */ public static void main(String[] args) throws Exception { AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance(ALGORITHM); paramGen.init(1024); AlgorithmParameters params = paramGen.generateParameters(); DHParameterSpec dhSpec = params.getParameterSpec(DHParameterSpec.class); System.out.println("l=" + dhSpec.getL()); System.out.println("g=" + dhSpec.getG()); System.out.println("p=" + dhSpec.getP()); }
/** Parse the key. Called by X509Key. */ protected void parseKeyBits() throws InvalidKeyException { try { AlgorithmParameters algParams = this.algid.getParameters(); params = algParams.getParameterSpec(ECParameterSpec.class); w = ECParameters.decodePoint(key, params.getCurve()); } catch (IOException e) { throw new InvalidKeyException("Invalid EC key", e); } catch (InvalidParameterSpecException e) { throw new InvalidKeyException("Invalid EC key", e); } }
public AlgorithmParameters getAlgParameters() { if (params == null && encodedParams != null) { try { params = AlgorithmParameters.getInstance(getAlgName()); params.init(encodedParams); } catch (NoSuchAlgorithmException ignore) { // FIXME throw exception? } catch (IOException ignore) { } } return params; }
private void testGCMGeneric(byte[] K, byte[] N, byte[] A, byte[] P, byte[] C) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException, IOException, InvalidParameterSpecException { Cipher eax = Cipher.getInstance("AES/GCM/NoPadding", "BC"); SecretKeySpec key = new SecretKeySpec(K, "AES"); // GCMParameterSpec mapped to AEADParameters and overrides default MAC // size GCMParameterSpec spec = new GCMParameterSpec(128, N); eax.init(Cipher.ENCRYPT_MODE, key, spec); eax.updateAAD(A); byte[] c = eax.doFinal(P); if (!areEqual(C, c)) { fail("JCE encrypt with additional data and GCMParameterSpec failed."); } eax = Cipher.getInstance("GCM", "BC"); eax.init(Cipher.DECRYPT_MODE, key, spec); eax.updateAAD(A); byte[] p = eax.doFinal(C); if (!areEqual(P, p)) { fail("JCE decrypt with additional data and GCMParameterSpec failed."); } AlgorithmParameters algParams = eax.getParameters(); byte[] encParams = algParams.getEncoded(); GCMParameters gcmParameters = GCMParameters.getInstance(encParams); if (!Arrays.areEqual(spec.getIV(), gcmParameters.getNonce()) || spec.getTLen() != gcmParameters.getIcvLen()) { fail("parameters mismatch"); } GCMParameterSpec gcmSpec = algParams.getParameterSpec(GCMParameterSpec.class); if (!Arrays.areEqual(gcmSpec.getIV(), gcmParameters.getNonce()) || gcmSpec.getTLen() != gcmParameters.getIcvLen() * 8) { fail("spec parameters mismatch"); } if (!Arrays.areEqual(eax.getIV(), gcmParameters.getNonce())) { fail("iv mismatch"); } }
private AlgorithmParameters checkParameters(Cipher c, byte[] salt, int iCount) throws InvalidParameterSpecException { AlgorithmParameters param = c.getParameters(); PBEParameterSpec spec = (PBEParameterSpec) param.getParameterSpec(PBEParameterSpec.class); if (!Arrays.areEqual(salt, spec.getSalt())) { fail("" + algorithm + "failed salt test"); } if (iCount != spec.getIterationCount()) { fail("" + algorithm + "failed count test"); } return param; }
protected AlgorithmParameters engineGetParameters() { if (engineParams == null) { if (paramSpec != null) { try { engineParams = AlgorithmParameters.getInstance("OAEP", "DFBC"); engineParams.init(paramSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } } return engineParams; }
public void testAES256CCM() throws Exception { byte[] data = "Eric H. Echidna".getBytes(); ASN1ObjectIdentifier macAlg = CMSAlgorithm.AES256_CCM; AlgorithmParameters algParams = AlgorithmParameters.getInstance("CCM", BC); algParams.init(new CCMParameters(Hex.decode("000102030405060708090a0b"), 16).getEncoded()); CMSAuthenticatedDataGenerator adGen = new CMSAuthenticatedDataGenerator(); X509CertificateHolder origCert = new X509CertificateHolder(_origCert.getEncoded()); adGen.setOriginatorInfo(new OriginatorInfoGenerator(origCert).generate()); adGen.addRecipientInfoGenerator( new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC)); CMSAuthenticatedData ad = adGen.generate( new CMSProcessableByteArray(data), new JceCMSMacCalculatorBuilder(macAlg) .setAlgorithmParameters(algParams) .setProvider(BC) .build()); assertTrue(ad.getOriginatorInfo().getCertificates().getMatches(null).contains(origCert)); RecipientInformationStore recipients = ad.getRecipientInfos(); assertEquals(ad.getMacAlgOID(), macAlg.getId()); Collection c = recipients.getRecipients(); assertEquals(1, c.size()); Iterator it = c.iterator(); while (it.hasNext()) { RecipientInformation recipient = (RecipientInformation) it.next(); assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); byte[] recData = recipient.getContent( new JceKeyTransAuthenticatedRecipient(_reciKP.getPrivate()).setProvider(BC)); assertTrue(Arrays.equals(data, recData)); assertEquals(16, ad.getMac().length); assertTrue(Arrays.equals(ad.getMac(), recipient.getMac())); } }
/* * Generate PBE Algorithm Parameters */ private AlgorithmParameters getAlgorithmParameters(String algorithm) throws IOException { AlgorithmParameters algParams = null; // create PBE parameters from salt and iteration count PBEParameterSpec paramSpec = new PBEParameterSpec(getSalt(), iterationCount); try { algParams = AlgorithmParameters.getInstance(algorithm); algParams.init(paramSpec); } catch (Exception e) { IOException ioe = new IOException("getAlgorithmParameters failed: " + e.getMessage()); ioe.initCause(e); throw ioe; } return algParams; }
protected AlgorithmParameters engineGetParameters() { if (engineParam == null) { if (engineParams != null) { String name = "IES"; try { engineParam = AlgorithmParameters.getInstance(name, BouncyCastleProvider.PROVIDER_NAME); engineParam.init(engineParams); } catch (Exception e) { throw new RuntimeException(e.toString()); } } } return engineParam; }
// see JCE spec protected AlgorithmParameters engineGetParameters() { if (iv == null) { return null; } IvParameterSpec ivSpec = new IvParameterSpec(iv); try { AlgorithmParameters params = AlgorithmParameters.getInstance(keyAlgorithm, P11Util.getSunJceProvider()); params.init(ivSpec); return params; } catch (GeneralSecurityException e) { // NoSuchAlgorithmException, NoSuchProviderException // InvalidParameterSpecException throw new ProviderException("Could not encode parameters", e); } }
private AlgorithmParameters getParameters() throws NoSuchAlgorithmException { AlgorithmParameters ap = AlgorithmParameters.getInstance(this.getAlgName()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); try { dOut.writeObject(infoObj.getEncryptionAlgorithm().getParameters()); dOut.close(); ap.init(bOut.toByteArray()); } catch (IOException e) { throw new NoSuchAlgorithmException("unable to parse parameters"); } return ap; }
private void tryKekAlgorithm(SecretKey kek, ASN1ObjectIdentifier algOid, byte[] encodedParameters) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, OperatorCreationException, IOException { byte[] data = "Eric H. Echidna".getBytes(); CMSAuthenticatedDataGenerator adGen = new CMSAuthenticatedDataGenerator(); byte[] kekId = new byte[] {1, 2, 3, 4, 5}; adGen.addRecipientInfoGenerator(new JceKEKRecipientInfoGenerator(kekId, kek).setProvider(BC)); AlgorithmParameters algParams = AlgorithmParameters.getInstance(CMSAlgorithm.DES_EDE3_CBC.getId(), "BC"); algParams.init(encodedParameters); CMSAuthenticatedData ad = adGen.generate( new CMSProcessableByteArray(data), new JceCMSMacCalculatorBuilder(CMSAlgorithm.DES_EDE3_CBC) .setAlgorithmParameters(algParams) .setProvider(BC) .build()); RecipientInformationStore recipients = ad.getRecipientInfos(); Collection c = recipients.getRecipients(); Iterator it = c.iterator(); assertEquals(ad.getMacAlgOID(), CMSAuthenticatedDataGenerator.DES_EDE3_CBC); assertEquals( ad.getMacAlgorithm().getParameters(), ASN1Primitive.fromByteArray(encodedParameters)); if (it.hasNext()) { RecipientInformation recipient = (RecipientInformation) it.next(); assertEquals(recipient.getKeyEncryptionAlgOID(), algOid.getId()); byte[] recData = recipient.getContent(new JceKEKAuthenticatedRecipient(kek).setProvider(BC)); assertTrue(Arrays.equals(data, recData)); assertTrue(Arrays.equals(ad.getMac(), recipient.getMac())); } else { fail("no recipient found"); } }
protected AlgorithmParameters engineGetParameters() { if (engineParams == null) { if (pbeSpec != null) { try { AlgorithmParameters engineParams = AlgorithmParameters.getInstance(pbeAlgorithm, BouncyCastleProvider.PROVIDER_NAME); engineParams.init(pbeSpec); return engineParams; } catch (Exception e) { return null; } } } return engineParams; }
/** * Create a new <code>EncryptedPrivateKeyInfo</code> object from raw encrypted data and the * parameters used for encryption. * * <p>The <code>encryptedData</code> array is cloned. * * @param params The encryption algorithm parameters. * @param encryptedData The encrypted key data. * @throws java.lang.IllegalArgumentException If the <code>encryptedData</code> array is empty * (zero-length). * @throws java.security.NoSuchAlgorithmException If the algorithm specified in the parameters is * not supported. * @throws java.lang.NullPointerException If <code>encryptedData</code> is null. */ public EncryptedPrivateKeyInfo(AlgorithmParameters params, byte[] encryptedData) throws IllegalArgumentException, NoSuchAlgorithmException { if (encryptedData.length == 0) { throw new IllegalArgumentException("0-length encryptedData"); } this.params = params; algName = params.getAlgorithm(); algOid = getOid(algName); this.encryptedData = (byte[]) encryptedData.clone(); }
@Override protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { if (params != null) { throw new InvalidAlgorithmParameterException( "unknown param type: " + params.getClass().getName()); } engineInitInternal(opmode, key); }
protected AlgorithmParameters engineGetParameters() { if (engineParams == null) { if (ivParam != null) { String name = cipher.getUnderlyingCipher().getAlgorithmName(); if (name.indexOf('/') >= 0) { name = name.substring(0, name.indexOf('/')); } try { engineParams = AlgorithmParameters.getInstance(name, BouncyCastleProvider.PROVIDER_NAME); engineParams.init(ivParam.getIV()); } catch (Exception e) { throw new RuntimeException(e.toString()); } } } return engineParams; }
protected AlgorithmParameters engineGenerateParameters() { byte[] iv = new byte[8]; if (random == null) { random = new SecureRandom(); } random.nextBytes(iv); AlgorithmParameters params; try { params = createParametersInstance("DES"); params.init(new IvParameterSpec(iv)); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; }
protected AlgorithmParameters engineGenerateParameters() { byte[] iv = new byte[8]; if (random == null) { random = new SecureRandom(); } random.nextBytes(iv); AlgorithmParameters params; try { params = AlgorithmParameters.getInstance("CAST5", BouncyCastleProvider.PROVIDER_NAME); params.init(new IvParameterSpec(iv)); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; }