简体   繁体   中英

OCB mode in Bouncy Castle Lightweight API

I've got a Java application that does AES-256-OCB. For this, the BouncyCastle crypto library is used. As-is, it uses the standard JCA interface, but this requires a special policy file to be installed to permit key sizes greater than 128 bits.

This is unsuitable in our environment, and it seems to me that we may be able to dodge this by using BouncyCastle's own lightweight API. I'm a bit confused by this API, however, and I was curious how I actually go about instantiating a cipher as AES/OCB/NoPadding.

I'm normally pretty good about reading documentation, but BouncyCastle's rather extensive options have me a bit confused.

How can I instantiate a BlockCipher object for 256-bit OCB mode with no padding, using the BouncyCastle lightweight API, and use this to encrypt and decrypt data? I've already got the key, IV and data as byte[] s.

Here's what I came up with reading through BouncyCastle's test code. It appears to function, although I've not compared the results with any test vectors.

Call with encrypt=true for encryption, encrypt=false for decryption. Set tagLen to the desired length of the AEAD tag in bits (eg. tagLen=128). Optionally set ad to associated data for validation, or leave null to skip. Returns a properly-sized byte array of resulting ciphertext or plaintext.

protected static byte[] processCipher(boolean encrypt, int tagLen, byte[] keyBytes, byte[] iv, byte[] in, byte[] ad) throws IllegalStateException, InvalidCipherTextException {
    KeyParameter key = new KeyParameter(keyBytes);
    AEADParameters params = new AEADParameters(key, tagLen, iv);
    AEADBlockCipher cipher = new OCBBlockCipher(new AESEngine(), new AESEngine());
    cipher.init(encrypt, params);

    byte[] out = new byte[cipher.getOutputSize(in.length)];
    if(ad != null) cipher.processAADBytes(ad, 0, ad.length);
    int offset = cipher.processBytes(in, 0, in.length, out, 0);
    offset += cipher.doFinal(out, offset);

    return out;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM