@Override public String decrypt(byte[] encrypted) { // Cipher cipher = null; String plain; try { // Security.addProvider(new BouncyCastlePQCProvider()); // cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", new BouncyCastlePQCProvider()); // cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new IvParameterSpec(iv)); // plain = new String(cipher.doFinal(encrypted), "UTF-8"); KeyParameter keyParam = new KeyParameter(encryptionKey); CipherParameters params = new ParametersWithIV(keyParam, iv); BlockCipherPadding padding = new PKCS7Padding(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CBCBlockCipher(new AESEngine()), padding); cipher.reset(); cipher.init(false, params); byte[] buffer = new byte[cipher.getOutputSize(encrypted.length)]; int len = cipher.processBytes(encrypted, 0, encrypted.length, buffer, 0); len += cipher.doFinal(buffer, len); byte[] out = Arrays.copyOfRange(buffer, 0, len); plain = new String(out, "UTF-8"); } catch (Exception e) { throw new RuntimeException("decrypt error in SimpleAesManaged", e); } return plain; }
/** * Generate a key with initialisation vector parameter derived from * the password, salt, and iteration count we are currently initialised * with. * * @param keySize the size of the key we want (in bits) * @param ivSize the size of the iv we want (in bits) * @return a ParametersWithIV object. * @exception IllegalArgumentException if keySize + ivSize is larger than the base hash size. */ public CipherParameters generateDerivedParameters( int keySize, int ivSize) { keySize = keySize / 8; ivSize = ivSize / 8; if ((keySize + ivSize) > digest.getDigestSize()) { throw new IllegalArgumentException( "Can't generate a derived key " + (keySize + ivSize) + " bytes long."); } byte[] dKey = generateDerivedKey(); return new ParametersWithIV(new KeyParameter(dKey, 0, keySize), dKey, keySize, ivSize); }
private static StreamCipher getSalsa20(byte[] key) { // Build stream cipher key MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException("SHA 256 not supported"); } byte[] key32 = md.digest(key); KeyParameter keyParam = new KeyParameter(key32); ParametersWithIV ivParam = new ParametersWithIV(keyParam, SALSA_IV); StreamCipher cipher = new Salsa20Engine(); cipher.init(true, ivParam); return cipher; }
static CipherParameters createCipherParameters(ASN1ObjectIdentifier algorithm, ExtendedDigest digest, int blockSize, PKCS12PBEParams pbeParams, char[] password) { PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(digest); pGen.init(PKCS12ParametersGenerator.PKCS12PasswordToBytes(password), pbeParams.getIV(), pbeParams.getIterations().intValue()); CipherParameters params; if (PKCS12PBEUtils.hasNoIv(algorithm)) { params = pGen.generateDerivedParameters(PKCS12PBEUtils.getKeySize(algorithm)); } else { params = pGen.generateDerivedParameters(PKCS12PBEUtils.getKeySize(algorithm), blockSize * 8); if (PKCS12PBEUtils.isDesAlg(algorithm)) { DESedeParameters.setOddParity(((KeyParameter)((ParametersWithIV)params).getParameters()).getKey()); } } return params; }
public void init( boolean forWrapping, CipherParameters param) { this.forWrapping = forWrapping; if (param instanceof ParametersWithRandom) { param = ((ParametersWithRandom) param).getParameters(); } if (param instanceof KeyParameter) { this.param = (KeyParameter)param; } else if (param instanceof ParametersWithIV) { this.iv = ((ParametersWithIV)param).getIV(); this.param = (KeyParameter)((ParametersWithIV) param).getParameters(); if (this.iv.length != 8) { throw new IllegalArgumentException("IV not equal to 8"); } } }
/** * Initialises the GMAC - requires a {@link ParametersWithIV} providing a {@link KeyParameter} * and a nonce. */ public void init(final CipherParameters params) throws IllegalArgumentException { if (params instanceof ParametersWithIV) { final ParametersWithIV param = (ParametersWithIV)params; final byte[] iv = param.getIV(); final KeyParameter keyParam = (KeyParameter)param.getParameters(); // GCM is always operated in encrypt mode to calculate MAC cipher.init(true, new AEADParameters(keyParam, macSizeBits, iv)); } else { throw new IllegalArgumentException("GMAC requires ParametersWithIV"); } }
public void init( boolean forEncryption, //ignored by this CTR mode CipherParameters params) throws IllegalArgumentException { if (params instanceof ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV)params; byte[] iv = ivParam.getIV(); System.arraycopy(iv, 0, IV, 0, IV.length); reset(); // if null it's an IV changed only. if (ivParam.getParameters() != null) { cipher.init(true, ivParam.getParameters()); } } else { throw new IllegalArgumentException("SIC mode requires ParametersWithIV"); } }
protected KeyParameter extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, byte[] derivedKey, byte[] encryptedContentEncryptionKey) throws CMSException { Wrapper keyEncryptionCipher = EnvelopedDataHelper.createRFC3211Wrapper(keyEncryptionAlgorithm.getAlgorithm()); keyEncryptionCipher.init(false, new ParametersWithIV(new KeyParameter(derivedKey), ASN1OctetString.getInstance(keyEncryptionAlgorithm.getParameters()).getOctets())); try { return new KeyParameter(keyEncryptionCipher.unwrap(encryptedContentEncryptionKey, 0, encryptedContentEncryptionKey.length)); } catch (InvalidCipherTextException e) { throw new CMSException("unable to unwrap key: " + e.getMessage(), e); } }
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) { try { byte[] dhSharedSecret = new byte[32]; Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey); for (int i = 0; i < 32; i++) { dhSharedSecret[i] ^= nonce[i]; } byte[] key = sha256().digest(dhSharedSecret); byte[] iv = new byte[16]; secureRandom.get().nextBytes(iv); PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher( new AESEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(true, ivAndKey); byte[] output = new byte[aes.getOutputSize(plaintext.length)]; int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0); ciphertextLength += aes.doFinal(output, ciphertextLength); byte[] result = new byte[iv.length + ciphertextLength]; System.arraycopy(iv, 0, result, 0, iv.length); System.arraycopy(output, 0, result, iv.length, ciphertextLength); return result; } catch (InvalidCipherTextException e) { throw new RuntimeException(e.getMessage(), e); } }
/** * Encrypt a plaintext using the given key and nonce. * * @param nonce a 24-byte nonce (cf. {@link #nonce(ByteString)}, {@link #nonce()}) * @param plaintext an arbitrary message * @return the ciphertext */ public ByteString seal(@Nonnull ByteString nonce, @Nonnull ByteString plaintext) { // initialize XSalsa20 final XSalsa20Engine xsalsa20 = new XSalsa20Engine(); xsalsa20.init(true, new ParametersWithIV(new KeyParameter(key), nonce.toByteArray())); // generate Poly1305 subkey final byte[] sk = new byte[32]; xsalsa20.processBytes(sk, 0, 32, sk, 0); // encrypt plaintext final byte[] out = new byte[plaintext.size() + 16]; xsalsa20.processBytes(plaintext.toByteArray(), 0, plaintext.size(), out, 16); // hash ciphertext and prepend mac to ciphertext final Poly1305 poly1305 = new Poly1305(); poly1305.init(new KeyParameter(sk)); poly1305.update(out, 16, plaintext.size()); poly1305.doFinal(out, 0); return ByteString.of(out); }
@Test public void compareModes() { BlockCipher engine = new AESEngine(); int blockSize = engine.getBlockSize(); BlockCipher ref = new SICBlockCipher(engine); // reference implementation BlockCipher uut = new CtrBlockCipher(engine); // unit under test PBEParametersGenerator gen = new PKCS5S2ParametersGenerator(); byte[] salt = new byte[blockSize]; // used as salt and cipher input new SecureRandom().nextBytes(salt); gen.init("top secret".getBytes(), salt, 1); ParametersWithIV param = (ParametersWithIV) gen.generateDerivedParameters( blockSize * 8, blockSize * 8); ref.init(true, param); uut.init(true, param); assertModes(ref, uut); ref.init(false, param); uut.init(false, param); assertModes(ref, uut); }
private byte[] encryptOrDecrypt(byte[] key, byte[] contents, boolean forEncryption) { // Credstash uses standard AES BlockCipher engine = new AESFastEngine(); // Credstash uses CTR mode StreamBlockCipher cipher = new SICBlockCipher(engine); cipher.init(forEncryption, new ParametersWithIV(new KeyParameter(key), INITIALIZATION_VECTOR)); byte[] resultBytes = new byte[contents.length]; int contentsOffset = 0; int resultOffset = 0; cipher.processBytes(contents, contentsOffset, contents.length, resultBytes, resultOffset); return resultBytes; }
public static byte[] aesDecrypt(byte[] ivCiphertext, byte[] myPrivateKey, byte theirPublicKey[]) { try { if (ivCiphertext.length < 16 || ivCiphertext.length % 16 != 0) { throw new InvalidCipherTextException("invalid ciphertext"); } byte[] iv = Arrays.copyOfRange(ivCiphertext, 0, 16); byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, 16, ivCiphertext.length); byte[] dhSharedSecret = new byte[32]; Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey); byte[] key = sha256().digest(dhSharedSecret); PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher( new AESEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(false, ivAndKey); byte[] output = new byte[aes.getOutputSize(ciphertext.length)]; int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0); plaintextLength += aes.doFinal(output, plaintextLength); byte[] result = new byte[plaintextLength]; System.arraycopy(output, 0, result, 0, result.length); return result; } catch (InvalidCipherTextException e) { throw new RuntimeException(e.getMessage(), e); } }
protected KeyParameter initRecordMAC(ChaChaEngine cipher, boolean forEncryption, long seqNo) { byte[] nonce = new byte[8]; TlsUtils.writeUint64(seqNo, nonce, 0); cipher.init(forEncryption, new ParametersWithIV(null, nonce)); byte[] firstBlock = new byte[64]; cipher.processBytes(firstBlock, 0, firstBlock.length, firstBlock, 0); // NOTE: The BC implementation puts 'r' after 'k' System.arraycopy(firstBlock, 0, firstBlock, 32, 16); KeyParameter macKey = new KeyParameter(firstBlock, 16, 32); Poly1305KeyGenerator.clamp(macKey.getKey()); return macKey; }
public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException { counter = 0; cfbEngine.init(forEncryption, params); this.forEncryption = forEncryption; if (params instanceof ParametersWithIV) { params = ((ParametersWithIV)params).getParameters(); } if (params instanceof ParametersWithRandom) { params = ((ParametersWithRandom)params).getParameters(); } if (params instanceof ParametersWithSBox) { params = ((ParametersWithSBox)params).getParameters(); } key = (KeyParameter)params; }
public TestResult perform() { byte[] kek1 = Hex.decode("fd04fd08060707fb0003fefffd02fe05"); byte[] iv1 = Hex.decode("c7d90059b29e97f7"); byte[] in1 = Hex.decode("b70a25fbc9d86a86050ce0d711ead4d9"); byte[] out1 = Hex.decode("70e699fb5701f7833330fb71e87c85a420bdc99af05d22af5a0e48d35f3138986cbaafb4b28d4f35"); // // note the RFC 3217 test specifies a key to be used with an effective key size of // 40 bits which is why it is done here - in practice nothing less than 128 bits should be used. // CipherParameters paramWrap = new ParametersWithRandom(new ParametersWithIV(new RC2Parameters(kek1, 40), iv1), new RFCRandom()); CipherParameters paramUnwrap = new RC2Parameters(kek1, 40); TestResult result = wrapTest(1, paramWrap, paramUnwrap, in1, out1); if (!result.isSuccessful()) { return result; } return new SimpleTestResult(true, getName() + ": Okay"); }
public void InitCiphers() { // create the ciphers // AES block cipher in CBC mode with padding encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher( new AESEngine())); decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher( new AESEngine())); // create the IV parameter ParametersWithIV parameterIV = new ParametersWithIV(new KeyParameter( key), IV); encryptCipher.init(true, parameterIV); decryptCipher.init(false, parameterIV); }
private void doCbc(byte[] key, byte[] iv, byte[] pt, byte[] expected) throws Exception { PaddedBufferedBlockCipher c = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SerpentEngine()), new PKCS7Padding()); byte[] ct = new byte[expected.length]; c.init(true, new ParametersWithIV(new KeyParameter(key), iv)); int l = c.processBytes(pt, 0, pt.length, ct, 0); c.doFinal(ct, l); if (!Arrays.areEqual(expected, ct)) { fail("CBC test failed"); } }
public void performTest() { chachaTest1(20, new ParametersWithIV(new KeyParameter(Hex.decode("80000000000000000000000000000000")), Hex.decode("0000000000000000")), set1v0_0, set1v0_192, set1v0_256, set1v0_448); chachaTest1(20, new ParametersWithIV(new KeyParameter(Hex.decode("00400000000000000000000000000000")), Hex.decode("0000000000000000")), set1v9_0, set1v9_192, set1v9_256, set1v9_448); chachaTest1(12, new ParametersWithIV(new KeyParameter(Hex.decode("80000000000000000000000000000000")), Hex.decode("0000000000000000")), chacha12_set1v0_0, chacha12_set1v0_192, chacha12_set1v0_256, chacha12_set1v0_448); chachaTest1(8, new ParametersWithIV(new KeyParameter(Hex.decode("80000000000000000000000000000000")), Hex.decode("0000000000000000")), chacha8_set1v0_0, chacha8_set1v0_192, chacha8_set1v0_256, chacha8_set1v0_448); chachaTest2(new ParametersWithIV(new KeyParameter(Hex.decode("0053A6F94C9FF24598EB3E91E4378ADD3083D6297CCF2275C81B6EC11467BA0D")), Hex.decode("0D74DB42A91077DE")), set6v0_0, set6v0_65472, set6v0_65536); chachaTest2(new ParametersWithIV(new KeyParameter(Hex.decode("0558ABFE51A4F74A9DF04396E93C8FE23588DB2E81D4277ACD2073C6196CBF12")), Hex.decode("167DE44BB21980E7")), set6v1_0, set6v1_65472, set6v1_65536); reinitBug(); skipTest(); }
public void performTest() { for (int i = 0; i < TEST_VECTORS.length; i++) { TestCase testCase = TEST_VECTORS[i]; Mac mac = new GMac(new GCMBlockCipher(new AESFastEngine()), testCase.getTag().length * 8); CipherParameters key = new KeyParameter(testCase.getKey()); mac.init(new ParametersWithIV(key, testCase.getIv())); testSingleByte(mac, testCase); testMultibyte(mac, testCase); } // Invalid mac size testInvalidMacSize(97); testInvalidMacSize(136); testInvalidMacSize(24); }
private void encryptBlock(byte[] key, byte[] iv, byte[] cekBlock) { BlockCipher engine = new CBCBlockCipher(new DESEngine()); engine.init(true, new ParametersWithIV(new KeyParameter(key), iv)); for (int i = 0; i < cekBlock.length; i += 8) { engine.processBlock(cekBlock, i, cekBlock, i); } for (int i = 0; i < cekBlock.length; i += 8) { engine.processBlock(cekBlock, i, cekBlock, i); } }
private void performTest(int number, TestCase testCase) { final byte[] plaintext = testCase.getPlaintext(); byte[] output = new byte[plaintext.length]; XSalsa20Engine engine = new XSalsa20Engine(); engine.init(false, new ParametersWithIV(new KeyParameter(testCase.getKey()), testCase.getIv())); engine.processBytes(testCase.getPlaintext(), 0, testCase.getPlaintext().length, output, 0); if (!Arrays.areEqual(testCase.getCiphertext(), output)) { fail("mismatch on " + number, new String(Hex.encode(testCase.getCiphertext())), new String(Hex.encode(output))); } }
public void init(boolean forWrapping, CipherParameters param) { this.forWrapping = forWrapping; if (param instanceof ParametersWithRandom) { param = ((ParametersWithRandom)param).getParameters(); } if (param instanceof KeyParameter) { this.param = (KeyParameter)param; } else if (param instanceof ParametersWithIV) { this.preIV = ((ParametersWithIV)param).getIV(); this.param = (KeyParameter)((ParametersWithIV)param).getParameters(); if (this.preIV.length != 4) { throw new IllegalArgumentException("IV length not equal to 4"); } } }
private void reinitBug() { KeyParameter key = new KeyParameter(Hex.decode("80000000000000000000000000000000")); ParametersWithIV parameters = new ParametersWithIV(key, Hex.decode("0000000000000000")); StreamCipher salsa = new Salsa20Engine(); salsa.init(true, parameters); try { salsa.init(true, key); fail("Salsa20 should throw exception if no IV in Init"); } catch (IllegalArgumentException e) { } }
@Override protected void _init(boolean isEncrypt, byte[] iv) { String keyStr = new String(key.getEncoded()); ParametersWithIV params = new ParametersWithIV( new KeyParameter(KeyHelper.generateKeyDigest(keyLength, keyStr)), iv ); cipher.init(isEncrypt, params); }
/** * initialise a Salsa20 cipher. * * @param forEncryption whether or not we are for encryption. * @param params the parameters required to set up the cipher. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init( boolean forEncryption, CipherParameters params) { /* * Salsa20 encryption and decryption is completely * symmetrical, so the 'forEncryption' is * irrelevant. (Like 90% of stream ciphers) */ if (!(params instanceof ParametersWithIV)) { throw new IllegalArgumentException("Salsa20 Init parameters must include an IV"); } ParametersWithIV ivParams = (ParametersWithIV) params; byte[] iv = ivParams.getIV(); if (iv == null || iv.length != 8) { throw new IllegalArgumentException("Salsa20 requires exactly 8 bytes of IV"); } if (!(ivParams.getParameters() instanceof KeyParameter)) { throw new IllegalArgumentException("Salsa20 Init parameters must include a key"); } KeyParameter key = (KeyParameter) ivParams.getParameters(); workingKey = key.getKey(); workingIV = iv; setKey(workingKey, workingIV); }
/** * Initialise the cipher and, possibly, the initialisation vector (IV). * If an IV isn't passed as part of the parameter, the IV will be all zeros. * * @param encrypting if true the cipher is initialised for * encryption, if false for decryption. * @param params the key and other data required by the cipher. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init( boolean encrypting, CipherParameters params) throws IllegalArgumentException { this.encrypting = encrypting; if (params instanceof ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV)params; byte[] iv = ivParam.getIV(); if (iv.length != blockSize) { throw new IllegalArgumentException("initialisation vector must be the same length as block size"); } System.arraycopy(iv, 0, IV, 0, iv.length); reset(); cipher.init(encrypting, ivParam.getParameters()); } else { reset(); cipher.init(encrypting, params); } }
/** * Initialise the cipher and, possibly, the initialisation vector (IV). * If an IV isn't passed as part of the parameter, the IV will be all zeros. * An IV which is too short is handled in FIPS compliant fashion. * * @param encrypting if true the cipher is initialised for * encryption, if false for decryption. * @param params the key and other data required by the cipher. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init( boolean encrypting, //ignored by this OFB mode CipherParameters params) throws IllegalArgumentException { if (params instanceof ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV)params; byte[] iv = ivParam.getIV(); if (iv.length < IV.length) { // prepend the supplied IV with zeros (per FIPS PUB 81) System.arraycopy(iv, 0, IV, IV.length - iv.length, iv.length); for (int i = 0; i < IV.length - iv.length; i++) { IV[i] = 0; } } else { System.arraycopy(iv, 0, IV, 0, IV.length); } reset(); cipher.init(true, ivParam.getParameters()); } else { reset(); cipher.init(true, params); } }
/** * Initialise the cipher and, possibly, the initialisation vector (IV). * If an IV isn't passed as part of the parameter, the IV will be all zeros. * An IV which is too short is handled in FIPS compliant fashion. * * @param encrypting if true the cipher is initialised for * encryption, if false for decryption. * @param params the key and other data required by the cipher. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init( boolean encrypting, CipherParameters params) throws IllegalArgumentException { this.encrypting = encrypting; if (params instanceof ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV)params; byte[] iv = ivParam.getIV(); if (iv.length < IV.length) { // prepend the supplied IV with zeros (per FIPS PUB 81) System.arraycopy(iv, 0, IV, IV.length - iv.length, iv.length); for (int i = 0; i < IV.length - iv.length; i++) { IV[i] = 0; } } else { System.arraycopy(iv, 0, IV, 0, IV.length); } reset(); cipher.init(true, ivParam.getParameters()); } else { reset(); cipher.init(true, params); } }