永发信息网

为什么解密后和明文不一样?

答案:2  悬赏:0  手机版
解决时间 2021-03-08 00:55
  • 提问者网友:喧嚣尘世
  • 2021-03-07 05:20
public class RSATest {

public static void main(String[] args)
{
try {
RSATest encrypt = new RSATest();
System.out.println("请输入你的明文:");
Scanner inputKey = new Scanner(System.in);
String encryptText = inputKey.next();
//String encryptText = "e";
KeyPair keyPair = encrypt.generateKey();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//System.out.println("私钥:"+privateKey);
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
//System.out.println("公钥:"+publicKey);
byte[] e = encrypt.encrypt(publicKey, encryptText.getBytes()); ,
byte[] de = encrypt.decrypt(privateKey, e);
System.out.println("加密后密文:"+toHexString(e));
System.out.println("解密后:"+toHexString(de));
} catch (Exception e) {
e.printStackTrace();
}
}
public KeyPair generateKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
return keyPair; }
protected byte[] encrypt(RSAPublicKey publicKey, byte[] data) {
if (publicKey != null) {

try { Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (Exception e)
{
e.printStackTrace();
}
}
return null;

}

protected byte[] decrypt(RSAPrivateKey privateKey, byte[] raw) {
if (privateKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(raw);

} catch (Exception e) {
e.printStackTrace(); }
}

return null;
}
public static String toHexString(byte[] b)
{
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++)
{ sb.append(HEXCHAr[(b[i] & 0xf0) >>> 4]);

sb.append(HEXCHAR[b[i] & 0x0f]); }
return sb.toString(); }
private static char[]
HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

}
最佳答案
  • 五星知识达人网友:渡鹤影
  • 2021-03-07 06:35
第一确定加密后的文件长度和加密前长度一致
因为如果一个字符‘a'加密后成了’\0‘的话,你这是用了strcat这样的函数就会默认把这个'\0'去掉的,
所以不要用strcat之类的函数,
要用指针。看看是不是这个问题。
全部回答
  • 1楼网友:西岸风
  • 2021-03-07 06:44
你说呢...
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯