@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; }
private byte[] encryptDESFile(String keys, byte[] plainText) { BlockCipher engine = new DESEngine(); 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 { cipher.doFinal(rv, tam); } catch (Exception ce) { ce.printStackTrace(); } return rv; }
public String testEncryptRijndael(String value,String key) throws DataLengthException, IllegalStateException, InvalidCipherTextException { BlockCipher engine = new RijndaelEngine(256); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine), new ZeroBytePadding()); byte[] keyBytes = key.getBytes(); cipher.init(true, new KeyParameter(keyBytes)); byte[] input = value.getBytes(); byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; int cipherLength = cipher.processBytes(input, 0, input.length, cipherText, 0); cipher.doFinal(cipherText, cipherLength); String result = new String(Base64.encode(cipherText)); //Log.e("testEncryptRijndael : " , result); return result; }
/** * Finishes and voids this cipher output stream. * Calling this method causes all remaining buffered bytes to get written * and padded if necessary. * Afterwards, this stream will behave as if it had been closed, although * the decorated stream may still be open. * * @throws IOException If {@code out} or {@code cipher} aren't properly * initialized, an I/O error occurs or the cipher * text is invalid because some required padding is missing. */ public void finish() throws IOException { final BufferedBlockCipher cipher = this.cipher; if (null == cipher) return; this.cipher = null; int cipherLen = cipher.getOutputSize(0); byte[] cipherOut = this.buffer; if (cipherLen > cipherOut.length) this.buffer = cipherOut = new byte[cipherLen]; try { cipherLen = cipher.doFinal(cipherOut, 0); } catch (InvalidCipherTextException ex) { throw new IOException(ex); } out.write(cipherOut, 0, cipherLen); }
private static byte[] EncryptAes256(byte[] data, byte[] encryptionKey) { try { KeyParameter keyParam = new KeyParameter(encryptionKey); BlockCipherPadding padding = new PKCS7Padding(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CBCBlockCipher(new AESEngine()), padding); cipher.reset(); cipher.init(true, keyParam); byte[] buffer = new byte[cipher.getOutputSize(data.length)]; int len = cipher.processBytes(data, 0, data.length, buffer, 0); len += cipher.doFinal(buffer, len); return Arrays.copyOfRange(buffer, 0, len); } catch (Exception e) { throw new RuntimeException("decrypt error in SimpleAesManaged", e); } }
public static PGPDataDecryptor createDataDecryptor(boolean withIntegrityPacket, BlockCipher engine, byte[] key) { final BufferedBlockCipher c = createStreamCipher(false, engine, withIntegrityPacket, key); return new PGPDataDecryptor() { public InputStream getInputStream(InputStream in) { return new CipherInputStream(in, c); } public int getBlockSize() { return c.getBlockSize(); } public PGPDigestCalculator getIntegrityCalculator() { return new SHA1PGPDigestCalculator(); } }; }
public PBESecretKeyDecryptor build(char[] passPhrase) { return new PBESecretKeyDecryptor(passPhrase, calculatorProvider) { public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] keyData, int keyOff, int keyLen) throws PGPException { try { BufferedBlockCipher c = BcUtil.createSymmetricKeyWrapper(false, BcImplProvider.createBlockCipher(encAlgorithm), key, iv); byte[] out = new byte[keyLen]; int outLen = c.processBytes(keyData, keyOff, keyLen, out, 0); outLen += c.doFinal(out, outLen); return out; } catch (InvalidCipherTextException e) { throw new PGPException("decryption failed: " + e.getMessage(), e); } } }; }
protected byte[] encryptSessionInfo(int encAlgorithm, byte[] key, byte[] sessionInfo) throws PGPException { try { BlockCipher engine = BcImplProvider.createBlockCipher(encAlgorithm); BufferedBlockCipher cipher = BcUtil.createSymmetricKeyWrapper(true, engine, key, new byte[engine.getBlockSize()]); byte[] out = new byte[sessionInfo.length]; int len = cipher.processBytes(sessionInfo, 0, sessionInfo.length, out, 0); len += cipher.doFinal(out, len); return out; } catch (InvalidCipherTextException e) { throw new PGPException("encryption failed: " + e.getMessage(), e); } }
private InputStream createCipherInputStream(byte[] data, Object cipher) { ByteArrayInputStream input = new ByteArrayInputStream(data); if (cipher instanceof BufferedBlockCipher) { return new CipherInputStream(input, (BufferedBlockCipher)cipher); } else if (cipher instanceof AEADBlockCipher) { return new CipherInputStream(input, (AEADBlockCipher)cipher); } else { return new CipherInputStream(input, (StreamCipher)cipher); } }
private String getName(Object cipher) { if (cipher instanceof BufferedBlockCipher) { return ((BufferedBlockCipher)cipher).getUnderlyingCipher().getAlgorithmName(); } else if (cipher instanceof AEADBlockCipher) { return ((AEADBlockCipher)cipher).getUnderlyingCipher().getAlgorithmName(); } else if (cipher instanceof StreamCipher) { return ((StreamCipher)cipher).getAlgorithmName(); } return null; }
private int getBlockSize(Object cipher) { if (cipher instanceof BlockCipher) { return ((BlockCipher)cipher).getBlockSize(); } else if (cipher instanceof BufferedBlockCipher) { return ((BufferedBlockCipher)cipher).getBlockSize(); } else if (cipher instanceof AEADBlockCipher) { return ((AEADBlockCipher)cipher).getUnderlyingCipher().getBlockSize(); } else if (cipher instanceof StreamCipher) { return 1; } return 0; }
private void basicTrial(BufferedBlockCipher cipher, KeyParameter param) throws InvalidCipherTextException { cipher.init(true, param); byte[] out = new byte[input.length]; int len1 = cipher.processBytes(input, 0, input.length, out, 0); cipher.doFinal(out, len1); if (!areEqual(out, output)) { fail("failed - " + "expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(out))); } }
private byte[] processCipher( BufferedBlockCipher cipher, byte[] input ) { byte[] output = new byte[cipher.getOutputSize( input.length )]; int cursor = cipher.processBytes( input, 0, input.length, output, 0 ); try { // cursor += cipher.doFinal( output, cursor ); if ( cursor != output.length ) { throw new InvalidCipherTextException( "Output size did not match cursor" ); } } catch ( InvalidCipherTextException e ) { LOGGER.error( "Could not encrypt/decrypt to/from cipher-text", e ); return null; } return output; }
public static byte[] processECB(byte[] key, boolean forEncryption, byte[] input) { final BufferedBlockCipher cipher = new BufferedBlockCipher(new TwofishEngine()); final KeyParameter kp = new KeyParameter(key); cipher.init(forEncryption, kp); final byte[] out = new byte[input.length]; final int len1 = cipher.processBytes(input, 0, input.length, out, 0); try { cipher.doFinal(out, len1); } catch (final CryptoException e) { throw new RuntimeException(e); } return out; }
public MultilayeredOutputStream(ArchiveInfoContext context, FileInventoryItem target) throws FileNotFoundException { this.target = target; this.topstream = new BlockWriterOutputStream( context.filePath, context.getBlockSize(), target, new BlockAllocationManager(context.getInventory(), target.getBlocks()) ); target.setEncryptionAlgorithm(context.getInventory().getDefaultEncryption()); if (target.isEncrypted()) { this.topstream = new CipherOutputStream( this.topstream, new BufferedBlockCipher(CipherBuilder.buildCipherForFile(target, true)) ); } else { target.setEncryptionData(null); } this.topstream = new DeflaterOutputStream(this.topstream, new Deflater(Deflater.BEST_SPEED)); }
public MultilayeredInputStream(ArchiveInfoContext context, FileInventoryItem target) { this.emptyFile = target.getActualSize() == 0; if (! emptyFile) { this.baseStream = new BlockReaderInputStream(context.filePath, context.getBlockSize(), target); this.topstream = this.baseStream; if (target.isEncrypted()) { this.topstream = new CipherInputStream( this.topstream, new BufferedBlockCipher(CipherBuilder.buildCipherForFile(target, false)) ); } this.topstream = new InflaterInputStream(this.topstream); } }
/** * Decrypts the given buffer using a block cipher. */ protected void blockDecrypt(ByteBuffer inPage, ByteBuffer outPage, int pageNumber) { BufferedBlockCipher cipher = decryptInit(getBlockCipher(), getCipherParams(pageNumber)); try { byte[] inArray = inPage.array(); int inLen = inArray.length; byte[] outArray = outPage.array(); processBytesFully(cipher, inArray, fill(outArray, 0), inLen); } catch(InvalidCipherTextException e) { throw new IllegalStateException(e); } }
/** * Encrypts the given buffer using a block cipher and returns the encrypted * buffer. */ protected ByteBuffer blockEncrypt(ByteBuffer buffer, int pageNumber) { BufferedBlockCipher cipher = encryptInit(getBlockCipher(), getCipherParams(pageNumber)); try { byte[] inArray = buffer.array(); int inLen = buffer.limit(); ByteBuffer encodeBuf = getTempBuffer(); processBytesFully(cipher, inArray, fill(encodeBuf.array(), 0), inLen); return encodeBuf; } catch(InvalidCipherTextException e) { throw new IllegalStateException(e); } }
@Override protected boolean verifyPassword(byte[] pwdBytes) { // OC: 2.3.4.9 BufferedBlockCipher cipher = decryptInit(getBlockCipher(), computeEncryptionKey(int2bytes(0))); byte[] verifier = decryptBytes(cipher, _verifier.getEncryptedVerifier()); byte[] verifierHash = fixToLength(decryptBytes(cipher, _verifier.getEncryptedVerifierHash()), _verifier.getVerifierHashSize()); byte[] testHash = fixToLength(hash(getDigest(), verifier), _verifier.getVerifierHashSize()); return Arrays.equals(verifierHash, testHash); }
private static InputStream CreateInputStream(InputStream s, boolean bEncrypt, byte[] pbKey, byte[] pbIV) { byte[] pbLocalIV = new byte[16]; System.arraycopy(pbIV, 0, pbLocalIV, 0, 16); byte[] pbLocalKey = new byte[32]; System.arraycopy(pbKey, 0, pbLocalKey, 0, 32); try { // Cipher r = Cipher.getInstance("AES/CBC/PKCS5Padding"); // IvParameterSpec ivspec = new IvParameterSpec(pbLocalIV); // SecretKeySpec keyspec = new SecretKeySpec(pbLocalKey, "AES"); // r.init(Cipher.DECRYPT_MODE, keyspec, ivspec); BlockCipher aes = AesEngines.createAesEngine(); KeyParameter key = new KeyParameter(pbLocalKey); ParametersWithIV iv = new ParametersWithIV(key, pbLocalIV); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(aes)); cipher.init(false, iv); return new CipherInputStream(s, cipher); } catch (Exception e) { throw new IllegalStateException(e); } }
private static OutputStream CreateOutputStream(OutputStream s, boolean bEncrypt, byte[] pbKey, byte[] pbIV) { byte[] pbLocalIV = new byte[16]; System.arraycopy(pbIV, 0, pbLocalIV, 0, 16); byte[] pbLocalKey = new byte[32]; System.arraycopy(pbKey, 0, pbLocalKey, 0, 32); try { BlockCipher aes = AesEngines.createAesEngine(); KeyParameter key = new KeyParameter(pbLocalKey); ParametersWithIV iv = new ParametersWithIV(key, pbLocalIV); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(aes)); cipher.init(true, iv); // Cipher r = Cipher.getInstance("AES/CBC/PKCS5Padding"); // IvParameterSpec ivspec = new IvParameterSpec(pbLocalIV); // SecretKeySpec keyspec = new SecretKeySpec(pbLocalKey, "AES"); // r.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); return new CipherOutputStream(s, cipher); } catch (Exception e) { throw new IllegalStateException(e); } }
/** * Returns the decrypted private key * * @param keyPhrase Key phrase used to derive the encryption key * @return Private key * @throws ECException Unable to complete a cryptographic function */ public BigInteger getPrivKey(String keyPhrase) throws ECException { KeyParameter aesKey = deriveKey(keyPhrase, salt); // // Decrypt the private key using the generated AES key // BigInteger privKey; try { ParametersWithIV keyWithIV = new ParametersWithIV(aesKey, iv); CBCBlockCipher blockCipher = new CBCBlockCipher(new AESEngine()); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); cipher.init(false, keyWithIV); int bufferLength = cipher.getOutputSize(encKeyBytes.length); byte[] outputBytes = new byte[bufferLength]; int length1 = cipher.processBytes(encKeyBytes, 0, encKeyBytes.length, outputBytes, 0); int length2 = cipher.doFinal(outputBytes, length1); int actualLength = length1 + length2; byte[] privKeyBytes = new byte[actualLength]; System.arraycopy(outputBytes, 0, privKeyBytes, 0, actualLength); privKey = new BigInteger(privKeyBytes); } catch (Exception exc) { throw new ECException("Unable to decrypt the private key", exc); } return privKey; }
public static byte[] encrypt(byte[] input, BufferedBlockCipher cipher) { synchronized(cipher) { cipher.reset(); byte[] cipherText = new byte[cipher.getOutputSize(input.length + pad.length)]; //Write out the pad int outputLen = cipher.processBytes(pad, 0, pad.length, cipherText, 0); outputLen += cipher.processBytes(input, 0, input.length, cipherText, outputLen); try { cipher.doFinal(cipherText, outputLen); } catch(CryptoException e) { Logger.die("process", e); } return cipherText; } }
public void testEdges() { byte[] key = genkey(); CryptoSession session = new CryptoSession(); session.logIn(key); BufferedBlockCipher encrypt = session.getEncrypter(); BufferedBlockCipher decrypt = session.getDecrypter(); //Blocks are generally 16 bytes, so hit around those edges. test(1, Hex.decode("11b11454f4b5160a78801cb8c5dcff511b11454f4b5160a78801cb8c5dcff5aa"), encrypt, decrypt); test(2, Hex.decode("11b11454f4b5160a78801cb8c5dcff511b11454f4b5160a78801cb8c5dcff5"), encrypt, decrypt); test(3, Hex.decode("11b11454f4b5160a78801cb8c5dcff511b11454f4b5160a78801cb8c5dcf"), encrypt, decrypt); test(4, Hex.decode("11b11454f4b5160a78801cb8c5dcffcfaa"), encrypt, decrypt); test(5, Hex.decode("11b11454f4b5160a78801cb8c5dcffcf"), encrypt, decrypt); test(6, Hex.decode("11b11454f4b5160a78801cb8c5dcff"), encrypt, decrypt); test(7, Hex.decode("11b114541f4b5160a78801cb8c"), encrypt, decrypt); test(8, Hex.decode("11b11454f4b5160a"), encrypt, decrypt); test(9, Hex.decode("a78801cb"), encrypt, decrypt); test(10, Hex.decode("12"), encrypt, decrypt); test(10, Hex.decode("00"), encrypt, decrypt); test(11, Hex.decode(""), encrypt, decrypt); }
private byte[] process(byte[] data, boolean encryption) throws DataLengthException { BlockCipher cipher = new AESEngine(); BlockCipherPadding padding = new ZeroBytePadding(); BufferedBlockCipher bufferedCipher = new PaddedBufferedBlockCipher(cipher, padding); bufferedCipher.init(encryption, key); byte[] output = new byte[bufferedCipher.getOutputSize(data.length)]; int bytesProcessed = bufferedCipher.processBytes(data, 0, data.length, output, 0); try { bufferedCipher.doFinal(output, bytesProcessed); return output; } catch (IllegalStateException | InvalidCipherTextException e) { e.printStackTrace(); } return null; }
private static byte[] crypt(final boolean encrypt, final byte[] bytes, final String password, final byte[] salt) throws InvalidCipherTextException { final PBEParametersGenerator keyGenerator = new PKCS12ParametersGenerator(new SHA256Digest()); keyGenerator.init(PKCS12ParametersGenerator.PKCS12PasswordToBytes(password.toCharArray()), salt, 20); final CipherParameters keyParams = keyGenerator.generateDerivedParameters(256, 128); final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); cipher.init(encrypt, keyParams); final byte[] processed = new byte[cipher.getOutputSize(bytes.length)]; int outputLength = cipher.processBytes(bytes, 0, bytes.length, processed, 0); outputLength += cipher.doFinal(processed, outputLength); final byte[] results = new byte[outputLength]; System.arraycopy(processed, 0, results, 0, outputLength); return results; }
/** * @return AES(BCrypt(clear_password, 10), SHA256(master_password_key)) */ public byte[] getHashedPassword(String clear_password) throws SecurityException { String tested_password = testIfPasswordIsStrong(clear_password); try { byte[] hashed = (BCrypt.hashpw(tested_password, BCrypt.gensalt(10))).getBytes("UTF-8"); BlockCipherPadding padding = new PKCS7Padding(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding); cipher.reset(); cipher.init(true, params); byte[] buf = new byte[cipher.getOutputSize(hashed.length)]; int len = cipher.processBytes(hashed, 0, hashed.length, buf, 0); len += cipher.doFinal(buf, len); byte[] out = new byte[len]; System.arraycopy(buf, 0, out, 0, len); return out; } catch (Exception e) { Loggers.Auth.error("Can't prepare password", e); } return null; }