作为项目实施的一部分,我做了以下事情: 1. Generete DSA密钥 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;
将错误显示为不可转换的类型
答案 0 :(得分:2)
您无法简单地将字节数组转换为PrivateKey实例。 您可以按KeyFactory
生成密钥答案 1 :(得分:0)
如果用此替换显式转换怎么办:
PrivateKey privateKey1 = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(val));