gpt4 book ai didi

java - 如何将字节数组转换为 DSA 私钥?

转载 作者:行者123 更新时间:2023-12-02 05:19:06 30 4
gpt4 key购买 nike

作为项目实现的一部分,我做了以下事情:1. 通用 DSA key 2.使用AES加密私钥3.保存到文件中4.打开文件并读取加密后的私钥5. 我尝试将读取的值转换为主键格式,但出现错误。我在这里附上上述步骤的代码:

public class Pgm {
public static void main(String[] args) {
try {
KeyPairGenerator dsa = KeyPairGenerator.getInstance("DSA");
SecureRandom random = new SecureRandom();
dsa.initialize(1024, random);
KeyPair keypair = dsa.generateKeyPair();
PrivateKey privateKey = (PrivateKey) keypair.getPrivate();
byte[] key = " �u���1�iw&a".getBytes();
Key aesKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
String currentDir = System.getProperty("user.dir");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] abc = privateKey.getEncoded();

byte[] encrypted = cipher.doFinal(abc);
// System.out.println("len="+encrypted.length());
File dir=new File(currentDir);
File private_file=new File(dir,"privatekey.txt");
if(!private_file.exists()){
private_file.createNewFile();
}
FileOutputStream fileos = new FileOutputStream(private_file);
ObjectOutputStream objectos = new ObjectOutputStream(fileos);
objectos.writeObject(encrypted);
objectos.close();
fileos.close();

File file_private = new File(dir,"privatekey.txt");
FileInputStream fileo = new FileInputStream(file_private);
ObjectInputStream objos = new ObjectInputStream(fileo);
Object obj = objos.readObject();
byte[] encrypted1= (byte[] )obj;
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted1));
if (decrypted.equals(new String(abc)))
System.out.println("true");
else
System.out.println("false");
Signature tosign = Signature.getInstance("DSA");
byte[] val = decrypted.getBytes();
PrivateKey privatekey1 = (PrivateKey)val;
tosign.initSign(privatekey1);

}
catch(Exception e)
{
e.printStackTrace();
}
}

}

' PrivateKey privatekey1 = (PrivateKey)val;

将错误显示为不可转换类型

最佳答案

您不能简单地将字节数组转换为 PrivateKey 实例。您可以通过 KeyFactory 生成 key

关于java - 如何将字节数组转换为 DSA 私钥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26648469/

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