如何将私钥从十六进制转换为PrivateKey对象?

时间:2013-12-12 13:38:25

标签: java rsa private-key asn.1

我为我的私钥生成了以下关键字符串:

"30820278020100300d06092a864886f70d0101010500048202623082025e02010002818100cabba8c50391583b66de7b4a70203674f8fc01012f66763db207fc09233cf69b9b6c8ee3c1a5ff1cc7f50df8a5ccf3aad4eddb66c0cb4a92d200e6b66803009d3095bd2cd94b6a4a47609c0bdade4f985f241d2f7d2b1b3ea14effb6714891f946ce4fa7c27f046ea112c145bad943788debf36c6ae7170a1f5bc0e6990827d1020301000102818100a82dfb38ccd7e3290c125e9706e34229d16f44ea15c75b299d2a1084080e87c9d8aabaf2e7ef6bee15570e2b0a68366fae4a4fab331eb21390511d138ebf86de658b9992c8c9e7207c73c983d944dff1f4aa5a472f83a477f6477410217720640acaeb439bf233dfdb2246e8e4e0fe813b6b691dc5b079bc9a0b9fa772dabacd024100ead2828c300bc418bede7ece9a9c011c26a99b750578ecb94a15a97cc6f6e152379955b46d6438bb015c94df0af019ca68cc06c0a07d496ecf52498d0548ca4b024100dd0448cdc4e65a62bb6c2d25a812e9809ed3842ca562bed13b8ee49af80a5338929bf3962674c1cb50417796e6a2e3462d2a094dd55af0bbc7c9df141078c4d302401e9ee8cb2310c5b77c5c4328e9dc6200abc1fe359a4b14836cf7ba2c3d3dc0501a53f26b1ec0aced25d64ecb6effb43d42c128384235543810ece80e6d9bfa55024100c028bd73ca41cd4c12501760aa24e747a0cf9e178323bb6c073051aa3b061f1d0cbaf2aa157d6610f312387bc6c2d07f6f3d2121bee276738d5d02cb5b16e569024100b07310d8ee67ea67de5d2906cdd50376d45095a5c5320d6c558e9409e4b3f4911464450b7e30279d4c167a44e0a4b83e71423c322ffecb063dea26fb055a1608"

如何将其转换回Java中的私钥对象?我已经尝试将这个字符串转换回字节数组,但我对如何继续这一点毫无头绪。

这是我将私钥转换为十六进制字符串的方式:

public static String getHexString(byte[] b){
  String result = "";
  for (int i = 0; i < b.length; i++){
    result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
   }
   return result;
 }

然后我在私钥上使用getEncoded()方法作为此方法的输入。

1 个答案:

答案 0 :(得分:4)

当您在RSA私钥上调用getEncoded()时,大多数提供商将返回PKCS#8格式的私钥。你的例子就是这种情况。

要撤消此过程,请使用KeyFactory PKCS8EncodedKeySpec,如下所示:

String key = "30820278020...1608"; // omitted for brevity

byte[] keyData = DatatypeConverter.parseHexBinary(key);
KeyFactory factory = KeyFactory.getInstance("RSA");
RSAPrivateKey privateKey = (RSAPrivateKey) factory
    .generatePrivate(new PKCS8EncodedKeySpec(keyData));

Signature signature = Signature.getInstance("SHA512withRSA");
signature.initSign(privateKey);
signature.update("Hello, World".getBytes());
System.out.println(DatatypeConverter.printHexBinary(signature.sign()));