0
我想創建RSA密鑰對並將其用於編碼/解碼數據。我的代碼很短,但我找不到任何錯誤。直接編碼/解碼不會產生原始數據
任何人都可以幫我找到我的問題嗎?
感謝您的每一個提示!
// Generate key pair.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024, new SecureRandom());
KeyPair keyPair = kpg.genKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// Data to encode/decode.
byte[] original = "The quick brown fox jumps over the lazy dog.".getBytes("UTF8");
// Encode data with public key.
Cipher cipherEncoder = Cipher.getInstance("RSA/ECB/NoPadding");
cipherEncoder.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encodedData = cipherEncoder.doFinal(original);
// Decode data with private key.
Cipher cipherDecoder = Cipher.getInstance("RSA/ECB/NoPadding");
cipherDecoder.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decodedData = cipherEncoder.doFinal(encodedData);
// Output.
System.out.println(new String("Original data: " + new String(original, "UTF8")));
System.out.println(new String("Encoded/decoded: " + new String(decodedData, "UTF8")));
最後的輸出似乎很古怪。
顯示輸出... – fge
教科書RSA(沒有填充)真的不安全。也不應該使用PKCS#1 v1.5填充(11字節開銷)。如今,建議使用OAEP(SHA1的開銷爲42字節)。 –
@ ArtjomB。感謝這個提示!你有我的OAEP代碼示例嗎? – Christian