문제

I generated the following key hexstring for my private key:

"30820278020100300d06092a864886f70d0101010500048202623082025e02010002818100cabba8c50391583b66de7b4a70203674f8fc01012f66763db207fc09233cf69b9b6c8ee3c1a5ff1cc7f50df8a5ccf3aad4eddb66c0cb4a92d200e6b66803009d3095bd2cd94b6a4a47609c0bdade4f985f241d2f7d2b1b3ea14effb6714891f946ce4fa7c27f046ea112c145bad943788debf36c6ae7170a1f5bc0e6990827d1020301000102818100a82dfb38ccd7e3290c125e9706e34229d16f44ea15c75b299d2a1084080e87c9d8aabaf2e7ef6bee15570e2b0a68366fae4a4fab331eb21390511d138ebf86de658b9992c8c9e7207c73c983d944dff1f4aa5a472f83a477f6477410217720640acaeb439bf233dfdb2246e8e4e0fe813b6b691dc5b079bc9a0b9fa772dabacd024100ead2828c300bc418bede7ece9a9c011c26a99b750578ecb94a15a97cc6f6e152379955b46d6438bb015c94df0af019ca68cc06c0a07d496ecf52498d0548ca4b024100dd0448cdc4e65a62bb6c2d25a812e9809ed3842ca562bed13b8ee49af80a5338929bf3962674c1cb50417796e6a2e3462d2a094dd55af0bbc7c9df141078c4d302401e9ee8cb2310c5b77c5c4328e9dc6200abc1fe359a4b14836cf7ba2c3d3dc0501a53f26b1ec0aced25d64ecb6effb43d42c128384235543810ece80e6d9bfa55024100c028bd73ca41cd4c12501760aa24e747a0cf9e178323bb6c073051aa3b061f1d0cbaf2aa157d6610f312387bc6c2d07f6f3d2121bee276738d5d02cb5b16e569024100b07310d8ee67ea67de5d2906cdd50376d45095a5c5320d6c558e9409e4b3f4911464450b7e30279d4c167a44e0a4b83e71423c322ffecb063dea26fb055a1608"

How can I convert this back to a private key object in 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.

도움이 되었습니까?

해결책

When you call getEncoded() on an RSA private key, most providers will return the private key in PKCS #8 format. This is the case with your example.

To reverse the process, use a KeyFactory with a PKCS8EncodedKeySpec as follows:

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top