[英]Simple RSA encrypt and decrypt message in JAVA
我已經嘗試了幾天,卻無法正常工作。 如果我有私鑰和公鑰對。 我只是嘗試使用公共密鑰加密郵件,然后使用私有密鑰解密。 我的代碼如下所示:
String message = "Secure Message";
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Key privateKey = keyPair.getPrivate();
Key publicKey = keyPair.getPublic();
Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptData = cipher.doFinal(message.getBytes());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptData = cipher.doFinal(encryptData);
System.out.println(encryptData.toString());
System.out.println(decryptData.toString());
但這似乎不起作用。 我得到的輸出是這樣的:
[B@4e33967b
[B@1cdc8d59
您的代碼有兩個非常小的問題,
// System.out.println(encryptData.toString());
// System.out.println(decryptData.toString());
System.out.println(Arrays.toString(encryptData));
System.out.println(new String(decryptData));
Object.toString()
,這基本上是hashCode(),實質上是一個引用地址。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.