java直接编码/解码不会产生原始数据
我想创建一个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")));
最后的结果似乎很奇怪
# 1 楼答案
首先,您使用
cipherEncoder
对数据进行解码。您可能打算使用cipherDecoder
。其次,在不使用填充的情况下使用RSA会出现问题(即,数据在开始时将有0
字节的负载)。我建议您至少使用PKCS1填充。下面是这些更改后的代码