gpt4 book ai didi

java - 解密压缩字符串

转载 作者:行者123 更新时间:2023-12-02 11:52:16 24 4
gpt4 key购买 nike

我正在尝试解密此证书。因为它很大,所以我在加密之前先对其进行压缩。为了解密,我先解密然后解压它。我真的很感激任何帮助。

这是输出:

[B@3ac42916

[B@5cad8086while the output should be the certification string

package test11;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;

public class Sample {

public static void main(String [] args) throws Exception {
// generate public and private keys
KeyPair keyPair = buildKeyPair();
PublicKey pubKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();


GzipUtil zipp = new GzipUtil();
// encrypt the message
String hour = "00";
String certificate="1"+","+"0336"+","+"RSA"+","+"CA 1552"+","+hour+","+pubKey+","+"RSA";
byte [] cert = GzipUtil.zip(certificate) ;
byte [] encrypted = encrypt(privateKey, cert.toString());
System.out.println(encrypted); // <<encrypted message>>

// decrypt the message
byte[] secret = decrypt(pubKey, encrypted);
String text= GzipUtil.unzip(secret);
System.out.println(text); // This is a secret message
}

public static KeyPair buildKeyPair() throws NoSuchAlgorithmException {
final int keySize = 2048;
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(keySize);
return keyPairGenerator.genKeyPair();
}

public static byte[] encrypt(PrivateKey privateKey, String message) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);

return cipher.doFinal(message.getBytes());
}

public static byte[] decrypt(PublicKey publicKey, byte [] encrypted) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);

return cipher.doFinal(encrypted);
}
}

最佳答案

问题是您不应该使用 toString() 直接将字节数组转换为字符串。

第一个错误是System.out.println(encrypted);,第二个错误是cert.toString(),两者都使用.toString() 来自 Object,它返回一个无意义的字符串。

Object.toString()的JavaDoc

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

当你想要显示字节数组的内容时,最好使用

System.out.println(Arrays.toString(encrypted));

此外,我会将加密更改为

public static byte[] encrypt(PrivateKey privateKey, byte[] message) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);

return cipher.doFinal(message);
}

并使用

byte [] encrypted = encrypt(privateKey, cert);

关于java - 解密压缩字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47809251/

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