本文介紹了Java 從 KeyPair 對象中檢索公鑰的實(shí)際值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我想問如何從 KeyPair 對象中檢索私鑰和公鑰的實(shí)際值,因?yàn)槲倚枰獙⑺鼈儗?dǎo)出并保存在數(shù)據(jù)庫中.
I wanted to ask how to retrieve the actual values of the private and public keys from the KeyPair object because i need to export them and save in a database.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair keyPair = kpg.genKeyPair();
System.out.println("Public key " + keyPair.getPublic());
System.out.println("Private key " + keyPair.getPrivate());
輸出是:
Public key Sun RSA public key, 1024 bits
modulus: 105712092415375085805423498639048173422142354311030811647243014925610093650322108853068042919471115278002432342007597147610508132502035047888382465733153739247741208519707861808073276783311634229563965825609200080862631487160732889423591650215084096832366499080850540875321197564283324922935557797293830551071
public exponent: 65537
Private key sun.security.rsa.RSAPrivateCrtKeyImpl@35e71
推薦答案
使用 keypair.getPublic.getEncoded()
或 keypair.getPrivate.getEncoded()
:
RSA 私鑰采用 PKCS#8 格式編碼,公鑰采用 X.509 格式編碼.
RSA private keys are encoded in PKCS#8 format, and public keys are encoded in X.509 format.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
PublicKey pub = keyPair.getPublic();
PrivateKey prv = keyPair.getPrivate();
byte[] pubBytes = pub.getEncoded();
byte[] prvBytes = prv.getEncoded();
// now save pubBytes or prvBytes
// to recover the key
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey prv_recovered = kf.generatePrivate(new PKCS8EncodedKeySpec(prvBytes));
PublicKey pub_recovered = kf.generatePublic(new X509EncodedKeySpec(pubBytes));
System.out.println("Private Key:
" + prv_recovered.toString());
System.out.println("Public Key:
" + pub_recovered.toString());
這篇關(guān)于Java 從 KeyPair 對象中檢索公鑰的實(shí)際值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!