gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:46:25 25 4
gpt4 key购买 nike

我想创建一个 RSA key 对并将其用于编码/解码数据。我的代码很短,但我找不到任何错误。

谁能帮我解决我的问题吗?

感谢您的每一个提示!

// 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")));

最后的输出似乎很奇怪。

最佳答案

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

关于java - 直接编码/解码不会产生原始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36253520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com