直接编码/解码不会产生原始数据

时间:2016-03-27 22:36:29

标签: java encryption rsa public-key-encryption

我想创建一个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 个答案:

答案 0 :(得分:2)

首先,您使用cipherEncoder解码数据。您可能打算使用cipherDecoder。其次,在没有填充的情况下使用RSA会遇到问题(即,您的数据在开始时将加载0个字节。我建议你至少使用PKCS1填充。以下是这些更改后的代码。

// 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/PKCS1Padding");
cipherEncoder.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encodedData = cipherEncoder.doFinal(original);

// Decode data with private key.
Cipher cipherDecoder = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipherDecoder.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decodedData = cipherDecoder.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")));