java读取openssl生成的private key文件生成密钥的问题

由 openssl生成的private key文件如下:
-----BEGIN RSA PRIVATE KEY-----
MIICXwIBAAKBgQDzxjNvQ4oUrDtPaPAnWiiixsiZSuNXIFhSwbKoaRWYLQSSCJPI
NuwCi2uRfQemOWp9EWUwxeQOwWxD3XUqZksCj7L7AUd8RXsIlB+Nejbw4KmSxbYn
39eGrf/ipWD4lrsUJMuuNi/QcIG3EsBjs63wxKzpA1+0diOAfHzXSJewTQIDAQAB
AoGBAND6GmHJrnemZnne5fF2UtuoOZNgJaAtNEpNjtDctQxtmzttavL6UjykNKTW
YFZZZjatUOgM3ULhAeTz1ltwsd9lzw+pF9CsyAOwyQNhjdO3VV+hmAinBm/32yPp
xkuqThS40pX5SRV5HZlLLm4dj90UA1bxrgr5LUQePPI9jzBBAkEA/7Q/9DDVKjie
f8Eeuh/ZElAjVve+DgmQJYkM2QOAHkCx2Zmw5hOq1TROVJUiJsSegSWWvMDnVA/w
bPboSFKOeQJBAPQOar6bj7EdSO5atrJg3jSA+SW/j30ljhERDOk3eI8bfgMYL7EG
QOG01VwoR3uyVEKY3n8i2WKGLuNwBe/Qa3UCQQCVODYeJaUwB2yPdz6cNVuy8Ss+
ZEL35CLHlMv3lLBedziSmLr/+Tg3RVf0yjbs0s8A5NOrgRM+HjMbE5eIJQ1ZAkEA
oWsPqvYUud5WqF+TSrPLBArxvsfOTcWTCzKtyWqI8I4McFuE3571NtN18rgpX2T5
Wfrl3kzcXs/FH2SuaIj/KQJBANFxrPGmyZNcGf0uiwm241+j3Pmy90+XUrmL1VYL
z1uGk3VsnRPo1SnO+f70zS3gfqodFk5Y9S0ZAj/p6uyeL2E=
-----END RSA PRIVATE KEY-----

用java代码要从这个文件中得到想要的priavtekey 可以先用命令
openssl pkcs8 -topk8 -inform PEM -outform DER -in rsa_pem.key -out pkcs8_der.key -nocrypt


对*.key文件进行转换,然后再读转换后的文件
File file = new File(keyfile);     //keyfile key文件的地址
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] tmpbuf = new byte[1024];
int count = 0;
while ((count = in.read(tmpbuf)) != -1) {
bout.write(tmpbuf, 0, count);
tmpbuf = new byte[1024];
}
in.close();
把读的输入流转变成自己想要的privatekey
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bout.toByteArray());
RSAPrivateKey privateKey = (RSAPrivateKey)keyFactory.generatePrivate(privateKeySpec);
这样就可以使用privatekey对自己的文件进行加密了
//进行加密
Signature dsa = Signature.getInstance("SHA1withRSA");      //采用SHA1withRSA加密
dsa.initSign(privateKey);
dsa.update(voucher.getBytes());    //voucher需要加密的String必须变成byte类型的
byte[] sig = dsa.sign();    
byRSA=toHexString(sig);   //加密后的byte类型变成十六进制的String

你可能感兴趣的:(java读取openssl生成的private key文件生成密钥的问题)