Mih*_*ala 4 encryption bouncycastle aes java-me
我想使用带有弹性城堡的AES算法在J2ME中加密和解密数据可以任何人给我示例代码
我想使用ECB和PKCS5Padding
提前致谢.
Jam*_*olk 19
我确信有一些例子,但我没有找到它们.以下是一些帮助您入门的提示.您需要学习如何将BC类连接在一起.首先,获取bouncycastle源代码,并准备好在遇到问题时查看它.它实际上非常易读,所以当文档很差时不要害怕检查它.例如,许多类需要CipherParameters
对象的实例,但文档很少指定任何更多细节.但是,在源代码中,很明显可以预期哪些实现类.
例如AESEngine
,选择一个AES引擎作为加密引擎.接下来选一个模式; ECB很少是正确的,例如,如果您选择CBC模式,CBCBlockCipher
则从AESEngine
对象创建一个对象.接下来,使用此对象创建一个PaddedBufferBlockCipher
对象.默认构造函数使用PKCS7填充,它与您想要的PKCS5填充相同.现在您需要创建一个对象来保存密钥和IV.这是CipherParameters
界面.您可以分两步创建对象.首先,KeyParameter
使用密钥创建对象.接下来,ParametersWithIV
使用KeyParameter
对象和IV 创建一个对象.此对象提供给对象的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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22604 次 |
最近记录: |