简体   繁体   English

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

[英]How do I convert a private key from hexadecimal to a PrivateKey object?

I generated the following key hexstring for my private key: 我为我的私钥生成了以下关键字符串:

""

How can I convert this back to a private key object in Java? 如何将其转换回Java中的私钥对象? I have tried converting this string back to a byte array but I'm clueless as to how I should continue. 我已经尝试将此字符串转换回字节数组,但我对如何继续这一点毫无头绪。

This is how I converted my private key to a hex string: 这是我将私钥转换为十六进制字符串的方式:

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;
 }

I then used the getEncoded() method on my private key as input for this method. 然后我在我的私钥上使用getEncoded()方法作为此方法的输入。

When you call getEncoded() on an RSA private key, most providers will return the private key in PKCS #8 format. 当您在RSA私钥上调用getEncoded()时,大多数提供程序将返回PKCS#8格式的私钥。 This is the case with your example. 您的示例就是这种情况。

To reverse the process, use a KeyFactory with a PKCS8EncodedKeySpec as follows: 要反转该过程,请使用带有PKCS8EncodedKeySpecKeyFactory ,如下所示:

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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM