2010-05-06 137 views
4

這裏是我的代碼RSA公鑰出口

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); 
    KeyPair myPair = kpg.generateKeyPair(); 
    PrivateKey k = myPair.getPrivate(); 
    System.out.print(k.serialVersionUID); 

    Cipher c = Cipher.getInstance("RSA"); 
    c.init(Cipher.ENCRYPT_MODE, myPair.getPublic()); 
    String myMessage = new String("Testing the message"); 

    byte[] bytes = c.doFinal(myMessage.getBytes()); 
    String tt = new String(bytes); 
    System.out.println(tt); 
    Cipher d = Cipher.getInstance("RSA"); 
    d.init(Cipher.DECRYPT_MODE, myPair.getPrivate()); 
    byte[] temp = d.doFinal(bytes); 
    String tst = new String(temp); 
    System.out.println(tst); 

我的問題是如何獲得的公鑰和存儲在別處

回答

4
PublicKey pubKey = myPair.getPublic(); 
byte[] keyBytes = pubKey.getEncoded(); 

保存keyBytes爲二進制文件或存儲在某個地方。

這樣做是爲了重建的關鍵,

KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
X509EncodedKeySpec pubKeySpec 
    = new X509EncodedKeySpec(keyBytes); 
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); 
+0

這就是我一直在尋找 – 2010-05-06 23:45:26