@Override protected StreamCipher getCipher() { String method = getMethod(); AESFastEngine engine = new AESFastEngine(); switch (method) { case CIPHER_AES_128_CFB: case CIPHER_AES_192_CFB: case CIPHER_AES_256_CFB: return new CFBBlockCipher(engine, 128); case CIPHER_AES_128_CFB8: case CIPHER_AES_192_CFB8: case CIPHER_AES_256_CFB8: return new CFBBlockCipher(engine, 8); case CIPHER_AES_128_OFB: case CIPHER_AES_192_OFB: case CIPHER_AES_256_OFB: return new OFBBlockCipher(engine, 128); default: throw new IllegalArgumentException(method); } }
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; }
static Wrapper createWrapper(int encAlgorithm) throws PGPException { switch (encAlgorithm) { case SymmetricKeyAlgorithmTags.AES_128: case SymmetricKeyAlgorithmTags.AES_192: case SymmetricKeyAlgorithmTags.AES_256: return new RFC3394WrapEngine(new AESFastEngine()); case SymmetricKeyAlgorithmTags.CAMELLIA_128: case SymmetricKeyAlgorithmTags.CAMELLIA_192: case SymmetricKeyAlgorithmTags.CAMELLIA_256: return new RFC3394WrapEngine(new CamelliaEngine()); default: throw new PGPException("unknown wrap algorithm: " + encAlgorithm); } }
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 testInvalidMacSize(int size) { try { GMac mac = new GMac(new GCMBlockCipher(new AESFastEngine()), size); mac.init(new ParametersWithIV(null, new byte[16])); fail("Expected failure for illegal mac size " + size); } catch (IllegalArgumentException e) { if (!e.getMessage().startsWith("Invalid value for MAC size")) { fail("Illegal mac size failed with unexpected message"); } } }
public SAES256v01(byte[] secretBytes, byte[] salt) { this.salt = salt.clone(); secretBytes = secretBytes.clone(); if (secretBytes.length != KEY_SIZE_BYTES) { secretBytes = Hashing.sha256().hashBytes(secretBytes).asBytes(); } try { KeyParameter key = new KeyParameter(secretBytes); AEADParameters params = new AEADParameters(key, MAC_SIZE_BITS, this.salt); this.encryptor = new GCMBlockCipher(new AESFastEngine()); this.encryptor.init(true, params); this.decryptor = new GCMBlockCipher(new AESFastEngine()); this.decryptor.init(false, params); } catch (Exception e) { throw new RuntimeException("could not create cipher for AES256", e); } finally { Arrays.fill(secretBytes, (byte) 0); } }
public CipherWriteStreamValidation(byte[] secretBytes, byte[] salt) { this.salt = salt.clone(); secretBytes = secretBytes.clone(); if (secretBytes.length != KEY_SIZE_BYTES) { secretBytes = Hashing.sha256().hashBytes(secretBytes).asBytes(); } try { KeyParameter key = new KeyParameter(secretBytes); AEADParameters params = new AEADParameters(key, MAC_SIZE_BITS, this.salt); this.encryptor = new GCMBlockCipher(new AESFastEngine()); this.encryptor.init(true, params); this.decryptor = new GCMBlockCipher(new AESFastEngine()); this.decryptor.init(false, params); } catch (Exception e) { throw new RuntimeException("could not create cipher for AES256", e); } finally { Arrays.fill(secretBytes, (byte) 0); } }
private void initCiphers(byte[] key, byte[] iv) { // get the keyBytes keyBytes = new byte[key.length]; System.arraycopy(key, 0, keyBytes, 0, key.length); keyP = new KeyParameter(keyBytes); // get the IV IV = new byte[blockSize]; System.arraycopy(iv, 0, IV, 0, IV.length); // create the ciphers // AES block cipher in CBC mode with ISO7816d4 padding encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher( new AESFastEngine()), new ISO7816d4Padding()); decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher( new AESFastEngine()), new ISO7816d4Padding()); // create the IV parameter ParametersWithIV parameterIV = new ParametersWithIV(keyP, IV); encryptCipher.init(true, parameterIV); decryptCipher.init(false, parameterIV); }
@Override public byte[] getMAC(byte[] data) { byte[] n = new byte[sscBytes.length + data.length]; System.arraycopy(sscBytes, 0, n, 0, sscBytes.length); System.arraycopy(data, 0, n, sscBytes.length, data.length); n = addPadding(n); BlockCipher cipher = new AESFastEngine(); Mac mac = new CMac(cipher, 64); mac.init(keyP); mac.update(n, 0, n.length); byte[] out = new byte[mac.getMacSize()]; mac.doFinal(out, 0); return out; }
private AesKeyId genKeyId() { try { final GCMBlockCipher gcm = new GCMBlockCipher(new AESFastEngine()); gcm.init(true, new AEADParameters( new KeyParameter(key), 128, KEYID_AD, KEYID_AD)); final byte[] ciphertext = new byte[gcm.getOutputSize(ZERO_BYTES.length)]; final int resp = gcm.processBytes(ZERO_BYTES, 0, ZERO_BYTES.length, ciphertext, 0); gcm.doFinal(ciphertext, resp); return new AesKeyId(ciphertext); } catch (final InvalidCipherTextException e) { // Should be impossible when we're encrypting! throw new RuntimeException( "Unexpected behaviour in crypto libraries", e); } }
public SequenceItem decrypt(final ConverterCatalog r, final AesPacket packet) throws InvalidInputException { final GCMBlockCipher gcm = new GCMBlockCipher(new AESFastEngine()); gcm.init(false, new AEADParameters( new KeyParameter(key), 128, packet.nonce, ZERO_BYTES)); final byte[] newtext = new byte[ gcm.getOutputSize(packet.ciphertext.length)]; final int pp = gcm.processBytes(packet.ciphertext, 0, packet.ciphertext.length, newtext, 0); try { gcm.doFinal(newtext, pp); } catch (final InvalidCipherTextException e) { throw new CryptographyException(e); } return ConvertUtils.fromBytes(r, SequenceItem.class, newtext); }
public static byte[] decrypt(byte[] key, byte[] data) { // TODO utilize GCMAES#decrypt method try { if (data.length < NONCE_LENGTH + TAG_LENGTH) { throw new IllegalArgumentException("data packet too short"); } int cipherTextLength = data.length - NONCE_LENGTH - TAG_LENGTH; byte[] nonce = Arrays.copyOf(data, NONCE_LENGTH); GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine()); AEADParameters parameters = new AEADParameters(new KeyParameter(key), TAG_LENGTH * 8, nonce); cipher.init(false, parameters); byte[] out = new byte[cipher.getOutputSize(cipherTextLength + TAG_LENGTH)]; int pos = cipher.processBytes(data, NONCE_LENGTH, data.length - NONCE_LENGTH, out, 0); pos += cipher.doFinal(out, pos); return Arrays.copyOf(out, pos); } catch (IllegalStateException | InvalidCipherTextException ex) { throw new IllegalArgumentException(ex); } }
public static byte[] decryptAESCBC(byte[] key, byte[] iv, byte[] data) { // AES CBC PKCS7 decrypt try { CipherParameters cipherParameters = new ParametersWithIV(new KeyParameter(key), iv); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()), new PKCS7Padding()); cipher.init(false, cipherParameters); byte[] buffer = new byte[cipher.getOutputSize(data.length)]; int pos = cipher.processBytes(data, 0, data.length, buffer, 0); pos += cipher.doFinal(buffer, pos); return Arrays.copyOf(buffer, pos); } catch (DataLengthException | IllegalStateException | InvalidCipherTextException ex) { throw new IllegalArgumentException("decrypt failed", ex); } }
/** * Encrypt or decrypt data with AES256. * * @param data The data to encrypt. * @param output The output to write the encrypted data to. * * @throws IOException If there is an error reading the data. */ private void decryptDataAES256(InputStream data, OutputStream output) throws IOException { byte[] iv = new byte[16]; // read IV from stream int ivSize = data.read(iv); if (ivSize == -1) { return; } if (ivSize != iv.length) { throw new IOException("AES initialization vector not fully read: only " + ivSize + " bytes read instead of " + iv.length); } PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CBCBlockCipher(new AESFastEngine())); cipher.init(false, new ParametersWithIV(new KeyParameter(encryptionKey), iv)); try (CipherInputStream cis = new CipherInputStream(data, cipher)) { org.apache.commons.io.IOUtils.copy(cis, output); } }
public static void main(String[] args) throws InterruptedException, IOException { // testTF_1024_1(); // testTF_1024_2(); testTF_512_1(); testTF_512_2(); // testTF_256_1(); // testTF_256_2(); System.out.println("Initialising test data."); byte[] input = new byte[DATA_SIZE]; rand.nextBytes(input); System.out.println("Init complete."); // speedTestCipher(new ThreefishEngine(ThreefishEngine.BLOCKSIZE_256), input); speedTestCipher(new ThreefishEngine(ThreefishEngine.BLOCKSIZE_512), input); // speedTestCipher(new Skein3FishEngine(), input); // speedTestCipher(new ThreefishEngine(ThreefishEngine.BLOCKSIZE_1024), input); // speedTestCipher(new ThreefishReferenceEngine(), input); speedTestCipher(new AESFastEngine(), input); // speedTestCipher(new TwofishEngine(), input); // speedTestCipher(new BlowfishEngine(), input); }
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(88); testInvalidMacSize(64); }
@Test public void testJavaCTRAES() { SRTPCipherCTR cipher = new SRTPCipherCTRJava(new AESFastEngine()); cipher.init(TV_Key); byte[] data = new byte[TV_Cipher_AES_1.length]; Arrays.fill(data, (byte) 0); byte[] iv = Arrays.copyOf(TV_IV_1, TV_IV_1.length); cipher.process(data, 0, data.length, iv); assertArrayEquals(data, TV_Cipher_AES_1); Arrays.fill(data, (byte) 0); iv = Arrays.copyOf(TV_IV_2, TV_IV_2.length); cipher.process(data, 0, data.length, iv); assertArrayEquals(data, TV_Cipher_AES_2); }
public ECB() { super(new BlockCipherProvider() { public BlockCipher get() { return new AESFastEngine(); } }); }
protected void init(boolean encryption, PlainFileKey fileKey) throws IllegalArgumentException { byte[] key = CryptoUtils.stringToByteArray(fileKey.getKey()); byte[] iv = CryptoUtils.stringToByteArray(fileKey.getIv()); AEADParameters parameters = new AEADParameters(new KeyParameter(key), 8 * TAG_SIZE, iv); realCipher = new GCMBlockCipher(new AESFastEngine()); realCipher.init(encryption, parameters); }
/** Creates a new instance of AESCipher */ public AESCipher(boolean forEncryption, byte[] key, byte[] iv) { BlockCipher aes = new AESFastEngine(); BlockCipher cbc = new CBCBlockCipher(aes); bp = new PaddedBufferedBlockCipher(cbc); KeyParameter kp = new KeyParameter(key); ParametersWithIV piv = new ParametersWithIV(kp, iv); bp.init(forEncryption, piv); }
private void randomTest( SecureRandom srng) throws InvalidCipherTextException { int DAT_LEN = srng.nextInt() >>> 22; // Note: JDK1.0 compatibility byte[] nonce = new byte[NONCE_LEN]; byte[] authen = new byte[AUTHEN_LEN]; byte[] datIn = new byte[DAT_LEN]; byte[] key = new byte[16]; srng.nextBytes(nonce); srng.nextBytes(authen); srng.nextBytes(datIn); srng.nextBytes(key); AESFastEngine engine = new AESFastEngine(); KeyParameter sessKey = new KeyParameter(key); EAXBlockCipher eaxCipher = new EAXBlockCipher(engine); AEADParameters params = new AEADParameters(sessKey, MAC_LEN * 8, nonce, authen); eaxCipher.init(true, params); byte[] intrDat = new byte[eaxCipher.getOutputSize(datIn.length)]; int outOff = eaxCipher.processBytes(datIn, 0, DAT_LEN, intrDat, 0); outOff += eaxCipher.doFinal(intrDat, outOff); eaxCipher.init(false, params); byte[] datOut = new byte[eaxCipher.getOutputSize(outOff)]; int resultLen = eaxCipher.processBytes(intrDat, 0, outOff, datOut, 0); eaxCipher.doFinal(datOut, resultLen); if (!areEqual(datIn, datOut)) { fail("EAX roundtrip failed to match"); } }
@Override public byte[] getMAC(byte[] key, byte[] data) { BlockCipher cipher = new AESFastEngine(); Mac mac = new CMac(cipher, 64); // TODO Padding der Daten KeyParameter keyP = new KeyParameter(key); mac.init(keyP); mac.update(data, 0, data.length); byte[] out = new byte[8]; mac.doFinal(out, 0); return out; }
/** * Dekodiert einen Block mit AES * * @param key * Byte-Array enthält den AES-Schlüssel * @param z * verschlüsselter Block * @return entschlüsselter block */ @Override public byte[] decryptBlock(byte[] key, byte[] z) { byte[] s = new byte[blockSize]; KeyParameter encKey = new KeyParameter(key); BlockCipher cipher = new AESFastEngine(); cipher.init(false, encKey); cipher.processBlock(z, 0, s, 0); return s; }
/** * Kodiert einen Block mit AES * * @param key * Byte-Array enthält den AES-Schlüssel * @param z * verschlüsselter Block * @return entschlüsselter block */ public byte[] encryptBlock(byte[] key, byte[] z) { byte[] s = new byte[blockSize]; KeyParameter encKey = new KeyParameter(key); BlockCipher cipher = new AESFastEngine(); cipher.init(true, encKey); cipher.processBlock(z, 0, s, 0); return s; }
public AesPacket encrypt(final SequenceItem message) { final byte[] nonce = Ec.randomBytes(12); final GCMBlockCipher gcm = new GCMBlockCipher(new AESFastEngine()); gcm.init(true, new AEADParameters( new KeyParameter(key), 128, nonce, ZERO_BYTES)); final byte[] plaintext = ConvertUtils.toBytes(message); final byte[] ciphertext = new byte[gcm.getOutputSize(plaintext.length)]; final int resp = gcm.processBytes(plaintext, 0, plaintext.length, ciphertext, 0); try { gcm.doFinal(ciphertext, resp); } catch (final InvalidCipherTextException e) { // Should be impossible when we're encrypting! throw new RuntimeException( "Unexpected behaviour in crypto libraries", e); } return new AesPacket(getKeyId(), nonce, ciphertext); }
/** * Returns decrypted data. * * @param key * @param nonce nonce/ IV * @param header * @param encryptedData * @param tag * @param optional optional AADBytes (post header) * @return decrypted data * @throws IllegalArgumentException on decryption exceptions * @throws NullPointerException on null arguments */ public static byte[] decrypt( byte[] key, byte[] nonce, byte[] header, byte[] encryptedData, byte[] tag, Optional<byte[]> optional) { try { GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine()); AEADParameters parameters = new AEADParameters(new KeyParameter(key), tag.length * 8, nonce, header); cipher.init(false, parameters); if (optional.isPresent()) { byte[] aadBytes = optional.get(); cipher.processAADBytes(aadBytes, 0, aadBytes.length); } byte[] out = new byte[cipher.getOutputSize(encryptedData.length + tag.length)]; int pos = cipher.processBytes(encryptedData, 0, encryptedData.length, out, 0); pos += cipher.processBytes(tag, 0, tag.length, out, pos); pos += cipher.doFinal(out, pos); return Arrays.copyOf(out, pos); } catch (IllegalStateException | InvalidCipherTextException | RuntimeCryptoException ex) { throw new IllegalStateException("GCM decrypt error", ex); } }
public static Optional<byte[]> unwrapAES(byte[] keyEncryptionKey, byte[] wrappedKey) { try { RFC3394WrapEngine engine = new RFC3394WrapEngine(new AESFastEngine()); engine.init(false, new KeyParameter(keyEncryptionKey)); return Optional.of(engine.unwrap(wrappedKey, 0, wrappedKey.length)); } catch (InvalidCipherTextException ex) { logger.debug("-- unwrap() - InvalidCipherTextException: {}", ex.getMessage()); return Optional.empty(); } }
public static synchronized RFC6637 secp521r1() { if (SECP521R1 == null) { SECP521R1 = create( "secp521r1", SHA512Digest::new, () -> new RFC3394WrapEngine(new AESFastEngine()), RFC6637Constants.ECDH, RFC6637Constants.AES_256, 0x20, RFC6637Constants.SHA512); } return SECP521R1; }
public static synchronized RFC6637 secp256r1() { if (SECP256R1 == null) { SECP256R1 = create( "secp256r1", SHA256Digest::new, () -> new RFC3394WrapEngine(new AESFastEngine()), RFC6637Constants.ECDH, RFC6637Constants.AES_128, 0x10, RFC6637Constants.SHA256); } return SECP256R1; }
private void validatePerms(PDEncryption encryption, int dicPermissions, boolean encryptMetadata) throws IOException { try { BufferedBlockCipher cipher = new BufferedBlockCipher(new AESFastEngine()); cipher.init(false, new KeyParameter(getEncryptionKey())); byte[] buf = new byte[cipher.getOutputSize(encryption.getPerms().length)]; int len = cipher.processBytes(encryption.getPerms(), 0, encryption.getPerms().length, buf, 0); len += cipher.doFinal(buf, len); byte[] perms = copyOf(buf, len); if (perms[9] != 'a' || perms[10] != 'd' || perms[11] != 'b') { LOG.warn("Verification of permissions failed (constant)"); } int permsP = perms[0] & 0xFF | (perms[1] & 0xFF) << 8 | (perms[2] & 0xFF) << 16 | (perms[3] & 0xFF) << 24; if (permsP != dicPermissions) { LOG.warn("Verification of permissions failed (" + String.format("%08X", permsP) + " != " + String.format("%08X", dicPermissions) + ")"); } if (encryptMetadata && perms[8] != 'T' || !encryptMetadata && perms[8] != 'F') { LOG.warn("Verification of permissions failed (EncryptMetadata)"); } } catch (DataLengthException | IllegalStateException | InvalidCipherTextException e) { throw new IOException(e); } }
/** * Create a new BufferedBlockCipher instance */ private static BufferedBlockCipher createBufferedBlockCipher(boolean par0, Key par1Key) { BufferedBlockCipher bufferedblockcipher = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8)); bufferedblockcipher.init(par0, new ParametersWithIV(new KeyParameter(par1Key.getEncoded()), par1Key.getEncoded(), 0, 16)); return bufferedblockcipher; }
/** * Create a new BufferedBlockCipher instance */ private static BufferedBlockCipher createBufferedBlockCipher(boolean par0, Key par1Key) { BufferedBlockCipher var2 = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8)); var2.init(par0, new ParametersWithIV(new KeyParameter(par1Key.getEncoded()), par1Key.getEncoded(), 0, 16)); return var2; }
public static void main(String[] args) { testMac(new HMac(new SHA1Digest()), new KeyParameter(generateNonce(20)), 3); testMac(new SkeinMac(SkeinMac.SKEIN_512, 128), new KeyParameter(generateNonce(64)), 2); testMac(new SipHash(), new KeyParameter(generateNonce(16)), 1); testMac(new CMac(new AESFastEngine()), new KeyParameter(generateNonce(16)), 3); testMac(new GMac(new GCMBlockCipher(new AESFastEngine())), new ParametersWithIV(new KeyParameter( generateNonce(16)), generateNonce(16)), 5); testMac(new Poly1305(new NullEngine(16)), new ParametersWithIV(generatePoly1305Key(), generateNonce(16)), 1); testMac(new Poly1305(new AESFastEngine()), new ParametersWithIV(generatePoly1305Key(), generateNonce(16)), 1); testMac(new Poly1305Reference(new NullEngine(16)), new ParametersWithIV(generatePoly1305Key(), generateNonce(16)), 1); }
private void testInvalidMacSize(int size) { try { GMac mac = new GMac(new GCMBlockCipher(new AESFastEngine()), size); mac.init(new ParametersWithIV(null, new byte[16])); fail("Expected failure for illegal mac size " + size); } catch (IllegalArgumentException e) { } }