aurelianr aurelianr - 2 months ago 10
Java Question

AES Encryption using CBC and PKCS5/7Padding using bouncy castle in java/android

I found this guide for java bouncy castle https://www.bouncycastle.org/fips/BCUserGuide.pdf

I tried to run the following example 3.3.1 AES Encryption using CBC and PKCS5/7Padding:

static byte[] encryptBytes(FipsOutputEncryptor outputEncryptor, byte[] plainText) throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
CipherOutputStream encOut = outputEncryptor.getEncryptingStream(bOut);
encOut.update(plainText);
encOut.close();
return bOut.toByteArray();
}

static byte[] decryptBytes(FipsInputDecryptor inputDecryptor,
byte[] cipherText) throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
InputStream encIn = inputDecryptor.getDecryptingStream(
new ByteArrayInputStream(cipherText));
int ch;
while ((ch = encIn.read()) >= 0)
{
bOut.write(ch);
}
return bOut.toByteArray();
}


// 3.3.1 AES Encryption using CBC and PKCS5/7Padding
// ensure a FIPS DRBG in use.
CryptoServicesRegistrar.setSecureRandom(
FipsDRBG.SHA512_HMAC.fromEntropySource(
new BasicEntropySourceProvider(new SecureRandom(), true))
.build(null, true));
byte[] iv = new byte[16];
CryptoServicesRegistrar.getSecureRandom().nextBytes(iv);
FipsSymmetricKeyGenerator<SymmetricSecretKey> keyGen =
new FipsAES.KeyGenerator(128,
CryptoServicesRegistrar.getSecureRandom());
SymmetricSecretKey key = keyGen.generateKey();
FipsSymmetricOperatorFactory<FipsAES.Parameters> fipsSymmetricFactory =
new FipsAES.OperatorFactory();
FipsOutputEncryptor<FipsAES.Parameters> outputEncryptor =
fipsSymmetricFactory.createOutputEncryptor(key,
FipsAES.CBCwithPKCS7.withIV(iv));

byte[] output = encryptBytes(outputEncryptor, new byte[16]);
FipsInputDecryptor<FipsAES.Parameters> inputDecryptor =
fipsSymmetricFactory.createInputDecryptor(key,
FipsAES.CBCwithPKCS7.withIV(iv));
byte[] plain = decryptBytes(inputDecryptor, output);


and the code don't compile.

I added the following libraries to the classpath

bcprov-jdk15on-155.jar
bcmail-jdk15on-155.jar
bcpg-jdk15on-155.jar
bcpkix-jdk15on-155.jar


The reason for I use the library is to integrate the AesCbcPkcs7 with my android application. Can you point me any hint in order to compile the above examples ?

Best Regards,
Aurelian

Answer

I tested with the following code - without bouncy castle - and works perfect:

import android.util.Base64;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by aurelian.rosca.
 */
public class EncryptionProvider2 {
    private final String characterEncoding = "UTF-8";
    private final String cipherTransformation = "AES/CBC/PKCS5Padding";
    private final String aesEncryptionAlgorithm = "AES";

    public  byte[] decrypt(byte[] cipherText, byte[] key, byte [] initialVector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
    {
        Cipher cipher = Cipher.getInstance(cipherTransformation);
        SecretKeySpec secretKeySpecy = new SecretKeySpec(key, aesEncryptionAlgorithm);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
        cipherText = cipher.doFinal(cipherText);
        return cipherText;
    }

    public byte[] encrypt(byte[] plainText, byte[] key, byte [] initialVector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
    {
        Cipher cipher = Cipher.getInstance(cipherTransformation);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, aesEncryptionAlgorithm);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        plainText = cipher.doFinal(plainText);
        return plainText;
    }

    private byte[] getKeyBytes(String key) throws UnsupportedEncodingException {
        byte[] keyBytes= new byte[16];
        byte[] parameterKeyBytes= key.getBytes(characterEncoding);
        System.arraycopy(parameterKeyBytes, 0, keyBytes, 0, Math.min(parameterKeyBytes.length, keyBytes.length));
        return keyBytes;
    }


    public String encrypt(String plainText, String key) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
        byte[] plainTextbytes = plainText.getBytes(characterEncoding);
        byte[] keyBytes = getKeyBytes(key);
        return Base64.encodeToString(encrypt(plainTextbytes,keyBytes, keyBytes), Base64.NO_WRAP);
    }


    public String decrypt(String encryptedText, String key) throws KeyException, GeneralSecurityException, GeneralSecurityException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException {
        byte[] cipheredBytes = Base64.decode(encryptedText, Base64.NO_WRAP);
        byte[] keyBytes = getKeyBytes(key);
        return new String(decrypt(cipheredBytes, keyBytes, keyBytes), characterEncoding);
    }
}