org.bouncycastle.crypto.CipherParameters Java Examples
The following examples show how to use
org.bouncycastle.crypto.CipherParameters.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BCStrongAESEncryption.java From Hive2Hive with MIT License | 6 votes |
private static byte[] processAESCipher(boolean encrypt, byte[] data, SecretKey key, byte[] initVector) throws DataLengthException, IllegalStateException, InvalidCipherTextException { // seat up engine, block cipher mode and padding AESEngine aesEngine = new AESEngine(); CBCBlockCipher cbc = new CBCBlockCipher(aesEngine); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbc); // apply parameters CipherParameters parameters = new ParametersWithIV(new KeyParameter(key.getEncoded()), initVector); cipher.init(encrypt, parameters); // process ciphering byte[] output = new byte[cipher.getOutputSize(data.length)]; int bytesProcessed1 = cipher.processBytes(data, 0, data.length, output, 0); int bytesProcessed2 = cipher.doFinal(output, bytesProcessed1); byte[] result = new byte[bytesProcessed1 + bytesProcessed2]; System.arraycopy(output, 0, result, 0, result.length); return result; }
Example #2
Source File: ECDSASigner.java From web3sdk with Apache License 2.0 | 6 votes |
@Override public void init(boolean forSigning, CipherParameters param) { SecureRandom providedRandom = null; if (forSigning) { if (param instanceof ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom) param; this.key = (ECPrivateKeyParameters) rParam.getParameters(); providedRandom = rParam.getRandom(); } else { this.key = (ECPrivateKeyParameters) param; } } else { this.key = (ECPublicKeyParameters) param; } this.random = initSecureRandom(forSigning && !kCalculator.isDeterministic(), providedRandom); }
Example #3
Source File: AESCBC.java From InflatableDonkey with MIT License | 6 votes |
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); } }
Example #4
Source File: BurstCryptoImpl.java From burstkit4j with Apache License 2.0 | 6 votes |
@Override public byte[] aesDecrypt(byte[] encrypted, byte[] signingKey, byte[] nonce) { if (signingKey.length != 32) { throw new IllegalArgumentException("Key length must be 32 bytes"); } try { if (encrypted.length < 16 || encrypted.length % 16 != 0) { throw new InvalidCipherTextException("invalid ciphertext"); } byte[] iv = Arrays.copyOfRange(encrypted, 0, 16); byte[] ciphertext = Arrays.copyOfRange(encrypted, 16, encrypted.length); for (int i = 0; i < 32; i++) { signingKey[i] ^= nonce[i]; } byte[] key = getSha256().digest(signingKey); 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); } }
Example #5
Source File: BurstCryptoImpl.java From burstkit4j with Apache License 2.0 | 6 votes |
@Override public byte[] aesEncrypt(byte[] plaintext, byte[] signingKey, byte[] nonce) { if (signingKey.length != 32) { throw new IllegalArgumentException("Key length must be 32 bytes"); } try { for (int i = 0; i < 32; i++) { signingKey[i] ^= nonce[i]; } byte[] key = getSha256().digest(signingKey); byte[] iv = new byte[16]; secureRandom.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); } }
Example #6
Source File: P11PlainRSASigner.java From xipki with Apache License 2.0 | 5 votes |
@Override public void init(boolean forEncryption, CipherParameters cipherParam) { if (!forEncryption) { throw new RuntimeCryptoException("verification mode not supported."); } if (!(cipherParam instanceof P11RSAKeyParameter)) { throw new IllegalArgumentException("invalid param type " + cipherParam.getClass().getName()); } this.param = (P11RSAKeyParameter) cipherParam; }
Example #7
Source File: DSAPlainDigestSigner.java From xipki with Apache License 2.0 | 5 votes |
@Override public void init(boolean forSigning, CipherParameters parameters) { this.forSigning = forSigning; AsymmetricKeyParameter param = (parameters instanceof ParametersWithRandom) ? (AsymmetricKeyParameter) ((ParametersWithRandom) parameters).getParameters() : (AsymmetricKeyParameter) parameters; Args.notNull(param, "param"); if (param instanceof ECPublicKeyParameters) { keyBitLen = ((ECPublicKeyParameters) param).getParameters().getCurve().getFieldSize(); } else if (param instanceof ECPrivateKeyParameters) { keyBitLen = ((ECPrivateKeyParameters) param).getParameters().getCurve().getFieldSize(); } else if (param instanceof DSAPublicKeyParameters) { keyBitLen = ((DSAPublicKeyParameters) param).getParameters().getQ().bitLength(); } else if (param instanceof DSAPrivateKeyParameters) { keyBitLen = ((DSAPrivateKeyParameters) param).getParameters().getQ().bitLength(); } else { throw new IllegalArgumentException("unknown parameters: " + param.getClass().getName()); } if (forSigning && !param.isPrivate()) { throw new IllegalArgumentException("Signing Requires Private Key."); } if (!forSigning && param.isPrivate()) { throw new IllegalArgumentException("Verification Requires Public Key."); } reset(); dsaSigner.init(forSigning, parameters); }
Example #8
Source File: HMac.java From google-authenticator with Apache License 2.0 | 5 votes |
public void init( CipherParameters params) { digest.reset(); byte[] key = ((KeyParameter)params).getKey(); if (key.length > blockLength) { digest.update(key, 0, key.length); digest.doFinal(inputPad, 0); for (int i = digestSize; i < inputPad.length; i++) { inputPad[i] = 0; } } else { System.arraycopy(key, 0, inputPad, 0, key.length); for (int i = key.length; i < inputPad.length; i++) { inputPad[i] = 0; } } outputPad = new byte[inputPad.length]; System.arraycopy(inputPad, 0, outputPad, 0, inputPad.length); for (int i = 0; i < inputPad.length; i++) { inputPad[i] ^= IPAD; } for (int i = 0; i < outputPad.length; i++) { outputPad[i] ^= OPAD; } digest.update(inputPad, 0, inputPad.length); }
Example #9
Source File: NativeRSAEngine.java From jna-gmp with Apache License 2.0 | 5 votes |
/** * initialise the RSA engine. * * @param forEncryption true if we are encrypting, false otherwise. * @param param the necessary RSA key parameters. */ public void init( boolean forEncryption, CipherParameters param) { if (core == null) { core = new NativeRSACoreEngine(); } core.init(forEncryption, param); }
Example #10
Source File: Crypto.java From mangooio with Apache License 2.0 | 5 votes |
/** * Encrypts a given plain text using the given key * * Encryption is done by using AES and CBC Cipher and a key length of 256 bit * * @param plainText The plain text to encrypt * @param key The key to use for encryption * @return The encrypted text or null if encryption fails */ public String encrypt(final String plainText, final String key) { Objects.requireNonNull(plainText, Required.PLAIN_TEXT.toString()); Objects.requireNonNull(key, Required.KEY.toString()); CipherParameters cipherParameters = new ParametersWithRandom(new KeyParameter(getSizedSecret(key).getBytes(StandardCharsets.UTF_8))); this.paddedBufferedBlockCipher.init(true, cipherParameters); return new String(base64Encoder.encode(cipherData(plainText.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8); }
Example #11
Source File: Crypto.java From mangooio with Apache License 2.0 | 5 votes |
/** * Decrypts an given encrypted text using the given key * * @param encrytedText The encrypted text * @param key The encryption key * @return The clear text or null if decryption fails */ public String decrypt(String encrytedText, String key) { Objects.requireNonNull(encrytedText, Required.ENCRYPTED_TEXT.toString()); Objects.requireNonNull(key, Required.KEY.toString()); CipherParameters cipherParameters = new ParametersWithRandom(new KeyParameter(getSizedSecret(key).getBytes(StandardCharsets.UTF_8))); this.paddedBufferedBlockCipher.init(false, cipherParameters); return new String(cipherData(base64Decoder.decode(encrytedText)), StandardCharsets.UTF_8); }
Example #12
Source File: GeoWaveEncryption.java From geowave with Apache License 2.0 | 5 votes |
private PaddedBufferedBlockCipher getCipher(final boolean encrypt) { final PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); final CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(getKey().getEncoded()), salt); cipher.init(encrypt, ivAndKey); return cipher; }
Example #13
Source File: XTSAESBlockCipher.java From InflatableDonkey with MIT License | 5 votes |
@Override public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException { if (params instanceof KeyParameter) { core.init(forEncryption, (KeyParameter) params); return; } throw new IllegalArgumentException("invalid params: " + params.getClass().getName()); }
Example #14
Source File: DPAESCBCCipher.java From InflatableDonkey with MIT License | 5 votes |
@Override public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException { if (!(params instanceof KeyParameter)) { throw new IllegalArgumentException("illegal params class: " + params.getClass()); } key = (KeyParameter) params; this.forEncryption = forEncryption; ivGenerator = new DPAESCBCBlockIVGenerator(key.getKey()); offset = 0; index = 0; }
Example #15
Source File: Rc4Md5Crypt.java From shadowsocks-android-java with Apache License 2.0 | 5 votes |
@Override protected CipherParameters getCipherParameters(byte[] iv) { byte[] bts = new byte[_keyLength + _ivLength]; System.arraycopy(_key.getEncoded(), 0, bts, 0, _keyLength); System.arraycopy(iv, 0, bts, _keyLength, _ivLength); return new KeyParameter(md5Digest(bts)); }
Example #16
Source File: CryptoUtils.java From warp10-platform with Apache License 2.0 | 5 votes |
/** * Unwrap byte [ ]. * * @param key the key * @param data the data * @return the byte [ ] */ public static byte[] unwrap(byte[] key, byte[] data) { // // Decrypt the encrypted data // AESWrapEngine engine = new AESWrapEngine(); CipherParameters params = new KeyParameter(key); engine.init(false, params); try { byte[] decrypted = engine.unwrap(data, 0, data.length); // // Unpad the decrypted data // PKCS7Padding padding = new PKCS7Padding(); int padcount = padding.padCount(decrypted); // // Remove padding // decrypted = Arrays.copyOfRange(decrypted, 0, decrypted.length - padcount); return decrypted; } catch (InvalidCipherTextException icte) { return null; } }
Example #17
Source File: RLPxConnectionFactory.java From incubator-tuweni with Apache License 2.0 | 5 votes |
private static EthereumIESEncryptionEngine forDecryption( SecretKey privateKey, PublicKey ephemeralPublicKey, Bytes iv, Bytes commonMac) { CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE); CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE); BasicAgreement agreement = new ECDHBasicAgreement(); agreement.init(privParam); byte[] agreementValue = BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam)); IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128); EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf = new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest()); kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV())); EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine( agreement, kdf, new HMac(new SHA256Digest()), commonMac.toArrayUnsafe(), new BufferedBlockCipher(new SICBlockCipher(new AESEngine()))); ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe()); engine.init(false, privParam, pubParam, cipherParameters); return engine; }
Example #18
Source File: Rc4Md5Crypt.java From shadowsocks-java with MIT License | 5 votes |
@Override protected CipherParameters getCipherParameters(byte[] iv) { byte[] bts = new byte[_keyLength + _ivLength]; System.arraycopy(_key.getEncoded(), 0, bts, 0, _keyLength); System.arraycopy(iv, 0, bts, _keyLength, _ivLength); return new KeyParameter(md5Digest(bts)); }
Example #19
Source File: CryptAeadBase.java From shadowsocks-java with MIT License | 5 votes |
protected CipherParameters getCipherParameters(boolean forEncryption) { // logger.debug("getCipherParameters subkey:{}",Arrays.toString(forEncryption ? encSubkey : decSubkey)); byte[] nonce; if (!isForUdp) { nonce = forEncryption ? Arrays.copyOf(encNonce, getNonceLength()) : Arrays.copyOf(decNonce, getNonceLength()); } else { nonce = ZERO_NONCE; } return new AEADParameters( new KeyParameter(forEncryption ? encSubkey : decSubkey), getTagLength() * 8, nonce ); }
Example #20
Source File: PacketTransformation.java From ts3j with Apache License 2.0 | 5 votes |
public byte[] decrypt(PacketHeader header, ByteBuffer buffer, int dataLen) throws InvalidCipherTextException { Pair<byte[], byte[]> parameters = computeParameters(header); byte[] headerWithoutMac = new byte[header.getSize() - MAC_LEN]; System.arraycopy(buffer.array(), MAC_LEN, headerWithoutMac, 0, headerWithoutMac.length); // Get the header without a MAC for the associated text field CipherParameters cipherParameters = new AEADParameters( new KeyParameter(parameters.getKey()), 8 * MAC_LEN, parameters.getValue(), headerWithoutMac ); byte[] result; int len; synchronized (cipher) { cipher.init(false, cipherParameters); result = new byte[cipher.getOutputSize(dataLen + MAC_LEN)]; len = cipher.processBytes(buffer.array(), header.getSize(), dataLen, result, 0); len += cipher.processBytes(buffer.array(), 0, MAC_LEN, result, len); len += cipher.doFinal(result, len); if (len != dataLen) throw new IllegalArgumentException(len + " != " + dataLen); } return result; }
Example #21
Source File: Ed25519BlockCipher.java From symbol-sdk-java with Apache License 2.0 | 5 votes |
public static BufferedBlockCipher setupBlockCipher( final byte[] sharedKey, final byte[] ivData, final boolean forEncryption) { // Setup cipher parameters with key and IV. final KeyParameter keyParam = new KeyParameter(sharedKey); final CipherParameters params = new ParametersWithIV(keyParam, ivData); // Setup AES cipher in CBC mode with PKCS7 padding. final BlockCipherPadding padding = new PKCS7Padding(); final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding); cipher.reset(); cipher.init(forEncryption, params); return cipher; }
Example #22
Source File: BouncyCastleV1CryptoProvider.java From paseto with MIT License | 5 votes |
private BufferedBlockCipher ase256CtrCipher(boolean forEncryption, byte[] key, byte[] iv) { BlockCipher engine = new AESEngine(); BufferedBlockCipher cipher = new BufferedBlockCipher(new SICBlockCipher(engine)); CipherParameters params = new ParametersWithIV(new KeyParameter(key), iv); cipher.init(forEncryption, params); return cipher; }
Example #23
Source File: RLPxConnectionFactory.java From cava with Apache License 2.0 | 5 votes |
private static EthereumIESEncryptionEngine forDecryption( SecretKey privateKey, PublicKey ephemeralPublicKey, Bytes iv, Bytes commonMac) { CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE); CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE); BasicAgreement agreement = new ECDHBasicAgreement(); agreement.init(privParam); byte[] agreementValue = BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam)); IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128); EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf = new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest()); kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV())); EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine( agreement, kdf, new HMac(new SHA256Digest()), commonMac.toArrayUnsafe(), new BufferedBlockCipher(new SICBlockCipher(new AESEngine()))); ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe()); engine.init(false, privParam, pubParam, cipherParameters); return engine; }
Example #24
Source File: RLPxConnectionFactory.java From cava with Apache License 2.0 | 5 votes |
private static EthereumIESEncryptionEngine forEncryption( PublicKey pubKey, Bytes iv, Bytes commonMac, KeyPair ephemeralKeyPair) { CipherParameters pubParam = new ECPublicKeyParameters(pubKey.asEcPoint(), CURVE); CipherParameters privParam = new ECPrivateKeyParameters(ephemeralKeyPair.secretKey().bytes().toUnsignedBigInteger(), CURVE); BasicAgreement agree = new ECDHBasicAgreement(); agree.init(privParam); BigInteger z = agree.calculateAgreement(pubParam); byte[] zbytes = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z); IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128); // Initialise the KDF. EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf = new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest()); kdf.init(new KDFParameters(zbytes, iesWithCipherParameters.getDerivationV())); EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine( agree, kdf, new HMac(new SHA256Digest()), commonMac.toArrayUnsafe(), new BufferedBlockCipher(new SICBlockCipher(new AESEngine()))); ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe()); engine.init(true, privParam, pubParam, cipherParameters); return engine; }
Example #25
Source File: SM2PreprocessSignerTest.java From gmhelper with Apache License 2.0 | 5 votes |
@Test public void test() throws CryptoException { AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter(); ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic(); SM2PreprocessSigner signer = new SM2PreprocessSigner(); CipherParameters pwr = new ParametersWithRandom(priKey, new SecureRandom()); signer.init(true, pwr); byte[] eHash1 = signer.preprocess(SRC_DATA, 0, SRC_DATA.length); byte[] sign1 = signer.generateSignature(eHash1); signer = new SM2PreprocessSigner(); signer.init(false, pubKey); byte[] eHash2 = signer.preprocess(SRC_DATA, 0, SRC_DATA.length); if (!Arrays.equals(eHash1, eHash2)) { Assert.fail(); } if (!signer.verifySignature(eHash1, sign1)) { Assert.fail(); } }
Example #26
Source File: SM4Util.java From gmhelper with Apache License 2.0 | 5 votes |
private static byte[] doMac(org.bouncycastle.crypto.Mac mac, byte[] key, byte[] iv, byte[] data) { CipherParameters cipherParameters = new KeyParameter(key); mac.init(new ParametersWithIV(cipherParameters, iv)); mac.update(data, 0, data.length); byte[] result = new byte[mac.getMacSize()]; mac.doFinal(result, 0); return result; }
Example #27
Source File: Digest.java From ontology-java-sdk with GNU Lesser General Public License v3.0 | 5 votes |
public static byte[] hmacSha512(byte[] keyBytes, byte[] text) { HMac hmac = new HMac(new SHA512Digest()); byte[] resBuf = new byte[hmac.getMacSize()]; CipherParameters pm = new KeyParameter(keyBytes); hmac.init(pm); hmac.update(text, 0, text.length); hmac.doFinal(resBuf, 0); return resBuf; }
Example #28
Source File: CryptSteamBase.java From shadowsocks-java with MIT License | 4 votes |
protected CipherParameters getCipherParameters(byte[] iv){ _decryptIV = Arrays.copyOfRange(iv,0,_ivLength); return new ParametersWithIV(new KeyParameter(_key.getEncoded()), _decryptIV); }
Example #29
Source File: CryptBase.java From shadowsocks-android-java with Apache License 2.0 | 4 votes |
protected CipherParameters getCipherParameters(byte[] iv){ _decryptIV = new byte[_ivLength]; System.arraycopy(iv, 0, _decryptIV, 0, _ivLength); return new ParametersWithIV(new KeyParameter(_key.getEncoded()), _decryptIV); }
Example #30
Source File: PacketTransformation.java From ts3j with Apache License 2.0 | 4 votes |
public ByteBuffer encrypt(Packet packet) { Pair<byte[], byte[]> parameters = computeParameters(packet.getHeader()); // Write header (this is temporary) ByteBuffer headerBuffer = packet.writeHeader( ByteBuffer .allocate(packet.getHeader().getSize()) .order(ByteOrder.BIG_ENDIAN) ); // Get the header without a MAC for the associated text field byte[] headerWithoutMac = new byte[packet.getHeader().getSize() - MAC_LEN]; System.arraycopy(headerBuffer.array(), MAC_LEN, headerWithoutMac, 0, headerWithoutMac.length); CipherParameters cipherParameters = new AEADParameters( new KeyParameter(parameters.getKey()), 8 * MAC_LEN, parameters.getValue(), headerWithoutMac ); int dataLen = packet.getBody().getSize(); ByteBuffer packetBuffer = packet.writeBody(ByteBuffer.allocate(dataLen).order(ByteOrder.BIG_ENDIAN)); byte[] result; int len; synchronized (cipher) { cipher.init(true, cipherParameters); result = new byte[cipher.getOutputSize(dataLen)]; len = cipher.processBytes(packetBuffer.array(), 0, dataLen, result, 0); try { len += cipher.doFinal(result, len); } catch (InvalidCipherTextException e) { throw new RuntimeException(e); } } ByteBuffer outputBuffer = ByteBuffer.allocate(MAC_LEN + headerWithoutMac.length + (len - MAC_LEN)); // Copy the mac to the packet header System.arraycopy(result, len - MAC_LEN, packet.getHeader().getMac(), 0, MAC_LEN); // MAC outputBuffer.put(result, len - MAC_LEN, MAC_LEN); // Rest of header outputBuffer.put(headerWithoutMac); // Encrypted body outputBuffer.put(result, 0, len - MAC_LEN); return outputBuffer; }