使用J2ME中的Bouncycastle示例进行AES加密/解密

时间:2010-11-22 08:38:48

标签: java-me encryption bouncycastle aes

我想使用具有弹性城堡的AES算法在J2ME中加密和解密数据 任何人都可以给我样本代码

我想将ECB与PKCS5Padding一起使用

先谢谢。

1 个答案:

答案 0 :(得分:19)

我确信有一些例子,但我没有找到它们。以下是一些帮助您入门的提示。您需要学习如何将BC类连接在一起。首先,获取bouncycastle源代码,并准备好在遇到问题时查看它。它实际上非常易读,所以当documentation很差时,不要害怕检查它。例如,许多类需要CipherParameters对象的实例,但文档很少指定任何更多细节。但是,在源代码中,很明显可以预期哪些实现类。

选择其中一个AES引擎(例如AESEngine)作为加密引擎。接下来选一个模式; ECB很少是正确的,例如,如果您选择CBC模式,则从CBCBlockCipher对象创建AESEngine对象。接下来,使用此对象创建PaddedBufferBlockCipher对象。默认构造函数使用PKCS7填充,它与您想要的PKCS5填充相同。现在您需要创建一个对象来保存密钥和IV。这是CipherParameters接口。您可以分两步创建对象。首先,使用密钥创建KeyParameter对象。接下来,使用ParametersWithIV对象和IV创建KeyParameter对象。此对象提供给init对象的PaddedBufferBlockCipher方法,然后您就可以开始使用了。

编辑

这是一个小例子:

private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
        throws Exception
{
    int minSize = cipher.getOutputSize(data.length);
    byte[] outBuf = new byte[minSize];
    int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
    int length2 = cipher.doFinal(outBuf, length1);
    int actualLength = length1 + length2;
    byte[] result = new byte[actualLength];
    System.arraycopy(outBuf, 0, result, 0, result.length);
    return result;
}

private static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv) throws Exception
{
    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
            new AESEngine()));
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
    aes.init(false, ivAndKey);
    return cipherData(aes, cipher);
}

private static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception
{
    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
            new AESEngine()));
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
    aes.init(true, ivAndKey);
    return cipherData(aes, plain);
}