List of usage examples for org.bouncycastle.crypto.modes CBCBlockCipher CBCBlockCipher
public CBCBlockCipher(BlockCipher cipher)
From source file:dorkbox.util.crypto.AesTest.java
License:Apache License
@SuppressWarnings("deprecation") @Test//from ww w. jav a2 s. c o m public void AesWithIVBlock() throws IOException { byte[] bytes = "hello, my name is inigo montoya".getBytes(); SecureRandom rand = new SecureRandom(entropySeed.getBytes()); PaddedBufferedBlockCipher aesEngine = new PaddedBufferedBlockCipher( new CBCBlockCipher(new AESFastEngine())); byte[] key = new byte[32]; // 256bit key byte[] iv = new byte[aesEngine.getUnderlyingCipher().getBlockSize()]; // note: the IV needs to be VERY unique! rand.nextBytes(key); rand.nextBytes(iv); byte[] encryptAES = CryptoAES.encryptWithIV(aesEngine, key, iv, bytes, logger); byte[] decryptAES = CryptoAES.decryptWithIV(aesEngine, key, encryptAES, logger); if (Arrays.equals(bytes, encryptAES)) { fail("bytes should not be equal"); } if (!Arrays.equals(bytes, decryptAES)) { fail("bytes not equal"); } }
From source file:dorkbox.util.crypto.AesTest.java
License:Apache License
@SuppressWarnings("deprecation") @Test//from w w w . jav a2 s . c om public void AesWithIVBlockStream() throws IOException { byte[] originalBytes = "hello, my name is inigo montoya".getBytes(); ByteArrayInputStream inputStream = new ByteArrayInputStream(originalBytes); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); SecureRandom rand = new SecureRandom(entropySeed.getBytes()); PaddedBufferedBlockCipher aesEngine = new PaddedBufferedBlockCipher( new CBCBlockCipher(new AESFastEngine())); byte[] key = new byte[32]; byte[] iv = new byte[16]; // note: the IV needs to be VERY unique! rand.nextBytes(key); // 256bit key rand.nextBytes(iv); // 128bit block size boolean success = CryptoAES.encryptStreamWithIV(aesEngine, key, iv, inputStream, outputStream, logger); if (!success) { fail("crypto was not successful"); } byte[] encryptBytes = outputStream.toByteArray(); inputStream = new ByteArrayInputStream(outputStream.toByteArray()); outputStream = new ByteArrayOutputStream(); success = CryptoAES.decryptStreamWithIV(aesEngine, key, inputStream, outputStream, logger); if (!success) { fail("crypto was not successful"); } byte[] decryptBytes = outputStream.toByteArray(); if (Arrays.equals(originalBytes, encryptBytes)) { fail("bytes should not be equal"); } if (!Arrays.equals(originalBytes, decryptBytes)) { fail("bytes not equal"); } }
From source file:dorkbox.util.crypto.EccTest.java
License:Apache License
@Test public void EccAesMode() throws IOException { // test AES encrypt mode SecureRandom secureRandom = new SecureRandom(); AsymmetricCipherKeyPair key1 = CryptoECC.generateKeyPair(CryptoECC.default_curve, secureRandom); AsymmetricCipherKeyPair key2 = CryptoECC.generateKeyPair(CryptoECC.default_curve, secureRandom); PaddedBufferedBlockCipher aesEngine1 = new PaddedBufferedBlockCipher( new CBCBlockCipher(new AESFastEngine())); PaddedBufferedBlockCipher aesEngine2 = new PaddedBufferedBlockCipher( new CBCBlockCipher(new AESFastEngine())); IESWithCipherParameters cipherParams = CryptoECC.generateSharedParametersWithCipher(secureRandom); IESEngine encrypt = CryptoECC.createEngine(aesEngine1); IESEngine decrypt = CryptoECC.createEngine(aesEngine2); // note: we want an ecc key that is AT LEAST 512 bits! (which is equal to AES 256) // using 521 bits from curve. CipherParameters private1 = key1.getPrivate(); CipherParameters public1 = key1.getPublic(); CipherParameters private2 = key2.getPrivate(); CipherParameters public2 = key2.getPublic(); byte[] message = Hex.decode( "123456784358754934597967249867359283792374987692348750276509765091834790abcdef123456784358754934597967249867359283792374987692348750276509765091834790abcdef123456784358754934597967249867359283792374987692348750276509765091834790abcdef"); // test stream mode byte[] encrypted = CryptoECC.encrypt(encrypt, private1, public2, cipherParams, message, logger); byte[] plaintext = CryptoECC.decrypt(decrypt, private2, public1, cipherParams, encrypted, logger); if (Arrays.equals(encrypted, message)) { fail("stream cipher test failed"); }/* www .j av a2 s . c om*/ if (!Arrays.equals(plaintext, message)) { fail("stream cipher test failed"); } }
From source file:edu.tamu.tcat.crypto.bouncycastle.SymmetricCipherBuilderImpl.java
License:Apache License
@Override public SymmetricCipher buildCipher(Cipher cipher, Mode mode, boolean encryption, byte[] key, byte[] iv) throws CipherException { ParametersWithIV cipherParameters = new ParametersWithIV(new KeyParameter(key), iv); BlockCipher underlyingCipher = null; switch (cipher) { case AES128://from ww w .ja va2s . c o m case AES192: case AES256: underlyingCipher = new AESEngine(); break; } BlockCipher blockCipher = null; switch (mode) { case CBC: blockCipher = new CBCBlockCipher(underlyingCipher); break; case GCM: throw new CipherException("GCM mode is authenticating encryption; use buildAEADCipher instead"); } BufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(blockCipher); bufferedBlockCipher.init(encryption, cipherParameters); return new BouncyCastleBlockCipher(bufferedBlockCipher); }
From source file:edu.wisc.doit.tcrypt.AbstractPublicKeyEncrypter.java
License:Apache License
protected BufferedBlockCipher createBlockCipher() { return new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())); }
From source file:EncriptDecriptArchivo.TestBouncy.java
License:Open Source License
public byte[] Encrypt(String keys, byte[] plainText) { byte[] key = keys.getBytes(); byte[] ptBytes = plainText; BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine)); cipher.init(true, new KeyParameter(key)); byte[] rv = new byte[cipher.getOutputSize(ptBytes.length)]; int tam = cipher.processBytes(ptBytes, 0, ptBytes.length, rv, 0); try {/*from ww w . j ava 2 s. co m*/ cipher.doFinal(rv, tam); } catch (DataLengthException | IllegalStateException | InvalidCipherTextException ce) { ce.printStackTrace(); } return rv; }
From source file:EncriptDecriptArchivo.TestBouncy.java
License:Open Source License
public byte[] Decrypt(String key2, byte[] cipherText) { byte[] key = key2.getBytes(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine)); cipher.init(false, new KeyParameter(key)); byte[] rv = new byte[cipher.getOutputSize(cipherText.length)]; int tam = cipher.processBytes(cipherText, 0, cipherText.length, rv, 0); try {/*from w ww .ja v a 2 s. c om*/ cipher.doFinal(rv, tam); } catch (DataLengthException | IllegalStateException | InvalidCipherTextException ce) { ce.printStackTrace(); } return rv; }
From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java
License:Apache License
/** * A method to create PKCS12 file that stores the certificates. * @param pfxOut: the output of pkcs12 file (in OutputStream) * @param key: private key that is associated with the credential * @param chain: chain of certificates (within the credential) * @param keyPasswd: key password//from w w w .j a v a 2 s . c o m * @throws Exception */ public static void createPKCS12FileBc(OutputStream pfxOut, AsymmetricKeyParameter key, X509CertificateHolder[] chain, char[] keyPasswd) throws Exception { OutputEncryptor encOut = new BcPKCS12PBEOutputEncryptorBuilder( PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())) .build(keyPasswd); PKCS12SafeBagBuilder taCertBagBuilder = null; PKCS12SafeBagBuilder caCertBagBuilder = null; PKCS12SafeBagBuilder eeCertBagBuilder = null; SubjectKeyIdentifier pubKeyId = null; // identify the type of certificate from the given certificate chain for (int i = 0; i < chain.length; i++) { Extensions exs = chain[i].getExtensions(); if (exs != null) { KeyUsage ku = KeyUsage.fromExtensions(exs); if (ku.toString().equals("KeyUsage: 0x" + Integer.toHexString(128 | 32))) { // end entity certificate eeCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]); BcX509ExtensionUtils extUtils = new BcX509ExtensionUtils(); eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Eric's Key")); pubKeyId = extUtils.createSubjectKeyIdentifier(chain[i].getSubjectPublicKeyInfo()); eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId); } else if (ku.toString().equals("KeyUsage: 0x" + Integer.toHexString(128 | 4 | 2))) { // intermediate certificate caCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]); caCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("BETaaS Intermediate Certificate")); } } else { // root certificate taCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]); taCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("BETaaS Primary Certificate")); } } // PKCS12SafeBagBuilder taCertBagBuilder = new PKCS12SafeBagBuilder(chain[2]); // PKCS12SafeBagBuilder caCertBagBuilder = new PKCS12SafeBagBuilder(chain[1]); // PKCS12SafeBagBuilder eeCertBagBuilder = new PKCS12SafeBagBuilder(chain[0]); // the ECPrivateKey, consists of the key itself and the ECParams BigInteger dPriv = ((ECPrivateKeyParameters) key).getD(); X9ECParameters ecParams = new X9ECParameters(((ECKeyParameters) key).getParameters().getCurve(), ((ECKeyParameters) key).getParameters().getG(), ((ECKeyParameters) key).getParameters().getN(), ((ECKeyParameters) key).getParameters().getH(), ((ECKeyParameters) key).getParameters().getSeed()); ECPrivateKey privParams = new ECPrivateKey(dPriv, ecParams); // include the ecParams AlgorithmIdentifier sigAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, ecParams); // PrivateKeyInfo keyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(key); PKCS12SafeBagBuilder keyBagBuilder = new PKCS12SafeBagBuilder(new PrivateKeyInfo(sigAlg, privParams), encOut); keyBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Eric's Key")); if (pubKeyId != null) keyBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId); PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder(); builder.addData(keyBagBuilder.build()); // no need to insert SHA1Digest() because it is the default Digest algorithm // check each of the certbagbuilder if (caCertBagBuilder != null && taCertBagBuilder != null && eeCertBagBuilder != null) { // include all types of certificate in the file --> root own's credential builder.addEncryptedData( new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(keyPasswd), new PKCS12SafeBag[] { eeCertBagBuilder.build(), caCertBagBuilder.build(), taCertBagBuilder.build() }); } else if (caCertBagBuilder != null && taCertBagBuilder != null && eeCertBagBuilder == null) { // only root and intermediate --> signer credential builder.addEncryptedData( new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(keyPasswd), new PKCS12SafeBag[] { caCertBagBuilder.build(), taCertBagBuilder.build() }); } else if (caCertBagBuilder == null && taCertBagBuilder == null) { // only end entity --> e.g. application, user, etc builder.addEncryptedData( new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(keyPasswd), new PKCS12SafeBag[] { eeCertBagBuilder.build() }); } else if (caCertBagBuilder != null && taCertBagBuilder == null && eeCertBagBuilder != null) { // only intermediate and end entity --> common GW certificate builder.addEncryptedData( new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(keyPasswd), new PKCS12SafeBag[] { eeCertBagBuilder.build(), caCertBagBuilder.build() }); } // PKCS12PfxPdu pfx = builder.build(new BcPKCS12MacCalculatorBuilder( // new SHA256Digest(), // new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)), keyPasswd); PKCS12PfxPdu pfx = builder.build(new BcPKCS12MacCalculatorBuilder(), keyPasswd); // make sure we don't include indefinite length encoding pfxOut.write(pfx.getEncoded(ASN1Encoding.DL)); pfxOut.close(); }
From source file:fc.xml.xas.security.SecUtil.java
License:Open Source License
public static BufferedBlockCipher getCipher(String id) { Verifier.checkNotNull(id);// w w w. j a va2 s . c om if (id.equals(AES_128_CIPHER)) { return new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new ISO10126d2Padding()); } else { return null; } }
From source file:freemail.OutboundContact.java
License:Open Source License
/** * Set up an outbound contact. Fetch the mailsite, generate a new SSK keypair and post an RTS message to the appropriate KSK. * Will block for mailsite retrieval and RTS insertion * * @return true for success//w w w . j a v a 2s . c o m */ private boolean init() throws ConnectionTerminatedException, InterruptedException { Logger.normal(this, "Initialising Outbound Contact " + address.toString()); // try to fetch get all necessary info. will fetch mailsite / generate new keys if necessary String initialslot = this.getCurrentLowestSlot(); SSKKeyPair commssk = this.getCommKeyPair(); if (commssk == null) return false; SSKKeyPair ackssk = this.getAckKeyPair(); RSAKeyParameters their_pub_key = this.getPubKey(); if (their_pub_key == null) return false; String rtsksk = this.getRtsKsk(); if (rtsksk == null) return false; StringBuffer rtsmessage = new StringBuffer(); // the public part of the SSK keypair we generated rtsmessage.append("commssk=" + commssk.pubkey + "\r\n"); rtsmessage.append("ackssk=" + ackssk.privkey + "\r\n"); rtsmessage.append("initialslot=" + initialslot + "\r\n"); rtsmessage.append("messagetype=rts\r\n"); // must include who this RTS is to, otherwise we're vulnerable to surreptitious forwarding rtsmessage.append("to=" + this.address.getSubDomain() + "\r\n"); // get our mailsite URI String our_mailsite_uri = account.getProps().get("mailsite.pubkey"); rtsmessage.append("mailsite=" + our_mailsite_uri + "\r\n"); rtsmessage.append("\r\n"); //FreemailLogger.normal(this,rtsmessage.toString()); // sign the message SHA256Digest sha256 = new SHA256Digest(); sha256.update(rtsmessage.toString().getBytes(), 0, rtsmessage.toString().getBytes().length); byte[] hash = new byte[sha256.getDigestSize()]; sha256.doFinal(hash, 0); RSAKeyParameters our_priv_key = AccountManager.getPrivateKey(account.getProps()); AsymmetricBlockCipher sigcipher = new RSAEngine(); sigcipher.init(true, our_priv_key); byte[] sig = null; try { sig = sigcipher.processBlock(hash, 0, hash.length); } catch (InvalidCipherTextException icte) { Logger.error(this, "Failed to RSA encrypt hash: " + icte.getMessage()); icte.printStackTrace(); return false; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { bos.write(rtsmessage.toString().getBytes()); bos.write(sig); } catch (IOException ioe) { ioe.printStackTrace(); return false; } // make up a symmetric key PaddedBufferedBlockCipher aescipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); // quick paranoia check! if (aescipher.getBlockSize() != AES_BLOCK_LENGTH) { // bouncycastle must have changed their implementation, so // we're in trouble Logger.normal(this, "Incompatible block size change detected in cryptography API! Are you using a newer version of the bouncycastle libraries? If so, we suggest you downgrade for now, or check for a newer version of Freemail."); return false; } byte[] aes_iv_and_key = this.getAESParams(); // now encrypt that with our recipient's public key AsymmetricBlockCipher enccipher = new RSAEngine(); enccipher.init(true, their_pub_key); byte[] encrypted_aes_params = null; try { encrypted_aes_params = enccipher.processBlock(aes_iv_and_key, 0, aes_iv_and_key.length); } catch (InvalidCipherTextException icte) { Logger.error(this, "Failed to perform asymmertic encryption on RTS symmetric key: " + icte.getMessage()); icte.printStackTrace(); return false; } // now encrypt the message with the symmetric key KeyParameter kp = new KeyParameter(aes_iv_and_key, aescipher.getBlockSize(), AES_KEY_LENGTH); ParametersWithIV kpiv = new ParametersWithIV(kp, aes_iv_and_key, 0, aescipher.getBlockSize()); aescipher.init(true, kpiv); byte[] encmsg = new byte[aescipher.getOutputSize(bos.toByteArray().length) + encrypted_aes_params.length]; System.arraycopy(encrypted_aes_params, 0, encmsg, 0, encrypted_aes_params.length); int offset = encrypted_aes_params.length; offset += aescipher.processBytes(bos.toByteArray(), 0, bos.toByteArray().length, encmsg, offset); try { aescipher.doFinal(encmsg, offset); } catch (InvalidCipherTextException icte) { Logger.error(this, "Failed to perform symmertic encryption on RTS data: " + icte.getMessage()); icte.printStackTrace(); return false; } // insert it! HighLevelFCPClient cli = new HighLevelFCPClient(); if (cli.slotInsert(encmsg, "KSK@" + rtsksk + "-" + DateStringFactory.getKeyString(), 1, "") < 0) { // safe to copy the message into the contact outbox though return false; } // remember the fact that we have successfully inserted the rts this.contactfile.put("status", "rts-sent"); // and remember when we sent it! this.contactfile.put("rts-sent-at", Long.toString(System.currentTimeMillis())); // and since that's been successfully inserted to that key, we can // throw away the symmetric key this.contactfile.remove("aesparams"); Logger.normal(this, "Succesfully initialised Outbound Contact"); return true; }