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

8nuwlpux  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(469)

我想创建一个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")));

最后的结果似乎很奇怪。

j1dl9f46

j1dl9f461#

首先,你在使用 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")));

相关问题