2013-12-12 62 views
1

我產生了我的私鑰以下關鍵比特產:如何將私鑰從十六進制轉換爲PrivateKey對象?

"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()方法對我的私人密鑰作爲此方法的輸入。

+0

你如何轉換鍵十六進制串?提供代碼 – Sach

+0

我使用代碼編輯了我的主題 –

回答

4

當您在RSA私鑰上調用getEncoded()時,大多數提供程序將返回PKCS#8格式的私鑰。你的例子就是這種情況。

的逆過程,使用KeyFactoryPKCS8EncodedKeySpec如下:

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())); 
相關問題