【发布时间】:2014-09-18 13:23:59
【问题描述】:
我在此链接上阅读 AES Encryption/Decryption with Bouncycastle Example in J2ME 关于如何使用 Bouncy Castle 提供的 AES 加密字符串。加密方法代码可以正常使用,但是解密不行。
谁能建议我如何解密加密的字符串?
我已经使用以下代码进行了测试:
import com.codename1.util.Base64;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
/**
*
* @author SAMUEL
*/
public class Tester {
static String strEnc = "Hi This is my String";
final static String strPassword = "password12345678";
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);
}
public static void main(String [] args) throws Exception{
byte[] enc= encrypt(strEnc.getBytes(),"password12345678".getBytes(), "password12345678".getBytes());
String encrypted = Base64.encode(enc);
System.out.println("Encrypted is:"+encrypted);
byte[] dec= decrypt(encrypted.getBytes(),"password12345678".getBytes() , "password12345678".getBytes());
System.out.println("Decrypted file is:"+dec);
}
}
输出是:
Encrypted is:sw0SrUIKe0DmS7sRd9+XMgtYg+BUiAfiOsdMw/Lo2RA=
异常堆栈跟踪是:
Exception in thread "main" org.bouncycastle.crypto.DataLengthException: last block incomplete in decryption
at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(PaddedBufferedBlockCipher.java:281)
at com.mycompany.myapp.Tester.cipherData(Tester.java:28)
at com.mycompany.myapp.Tester.decrypt(Tester.java:40)
at com.mycompany.myapp.Tester.main(Tester.java:57)
【问题讨论】:
-
首先,这个问题包含的信息太少了。其次,我想知道您是否甚至阅读了您所指向的答案下方的 cmets。
-
它包含指向我遇到的主要问题的链接.. 我做到了,它可以很好地用于加密,但我在解密时遇到问题,这就是我问的原因
-
呃,哪里又是你的代码?如果您可以编辑您的问题,我很乐意撤回我的近距离投票(这些投票主要是在我们无法回答问题时给予,如果我们不想回答问题则不是那么多) .
-
我是这个网站的新手,所以我尝试发布我的代码,但由于未知原因,我不能。但这是我在代号论坛上的代码...groups.google.com/forum/…
标签: encryption encoding java-me aes bouncycastle