【发布时间】:2012-11-25 22:36:22
【问题描述】:
我正在编写一个在 Android 中使用 RSA 的程序。我有以下问题: 我正在获取 RSA 密钥:
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
使用加密函数对测试字符串进行加密:
String test ="test";
byte[] testbytes = test.getBytes();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(testbytes);
String s = new String(cipherData);
Log.d("testbytes after encryption",s);
在解密函数中,我将数据解密回来以获取原始字符串
Cipher cipher2 = Cipher.getInstance("RSA");
cipher2.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainData = cipher.doFinal(cipherData);
String p = new String(plainData);
Log.d("decrypted data is:",p);
日志中打印出来的'p'中的数据与原字符串“test”不匹配。我哪里错了?
【问题讨论】:
-
那么日志中打印出什么?如果您的密钥不匹配或密码乱码,您会得到一个异常,而不是错误的答案。
-
另请注意,
cipherData将是一个类似随机的二进制字符串,因此仅使用原始字节 (String s = new String(cipherData);) 将其转换为字符串可能会给您带来奇怪的结果。
标签: java android encryption rsa