2016-11-27 70 views
0

有誰知道是否有方法將公鑰以pgp公鑰格式轉換爲X.509密鑰格式?也許用Bouncy Castle或者熟悉的東西?轉換PGP公鑰

因爲現在我能夠使用X509EncodedKeySpecs和PublicKey解碼X.509公鑰,但這不適用於PGP密鑰格式。

byte[] decodeValue = Base64.decode(schluesselstring.getBytes(), Base64.DEFAULT); 
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(decodeValue); 
try { 
    KeyFactory keyFact = KeyFactory.getInstance("RSA"); 
    try { 
     PublicKey publicKey = keyFact.generatePublic(pubKeySpec); 
     schluessel = "schluessel"; 
     Log.d("TEST", "publicKey = " + publicKey.toString()); 
     Log.d("TEST", "Algorithm = " + publicKey.getAlgorithm()); 
     Log.d("TEST", "Format = " + publicKey.getFormat()); 
     } 
    catch... 
    } 

當我嘗試在PGP密鑰上使用此代碼時,我收到一條錯誤消息,因爲它不是ANSC.1。我也嘗試使用不同的KeySpecs,但都沒有工作。

回答

1

「X.509」(SPKI)和「PKCS8」密鑰以及證書等其他內容使用的標準是Abstract Syntax Notation One ASN.1。標準Java加密不處理PGP,但是BouncyCastle(bcpg)可以做到這一點很好:

static void SO40831894 (String infile, String outfile) throws Exception { 
    // adapted from org.bouncycastle.openpgp.examples.PubringDump 
    try (InputStream in = new FileInputStream (infile)){ 
     PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(
       PGPUtil.getDecoderStream(in), new JcaKeyFingerprintCalculator()); 
     Iterator<PGPPublicKeyRing> rIt = pubRings.getKeyRings(); 
     while (rIt.hasNext()){ 
      PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next(); 
      Iterator<PGPPublicKey> it = pgpPub.getPublicKeys(); 
      while (it.hasNext()){ 
       PGPPublicKey pgpKey = (PGPPublicKey)it.next(); 
       System.out.println(pgpKey.getClass().getName() 
         + " KeyID: " + Long.toHexString(pgpKey.getKeyID()) 
         + " type: " + pgpKey.getAlgorithm() 
         + " fingerprint: " + new String(Hex.encode(pgpKey.getFingerprint()))); 
       BCPGKey bcKey = pgpKey.getPublicKeyPacket().getKey(); 
       /*System.out.println (bcKey.getClass().getName());*/ 
       if(bcKey instanceof RSAPublicBCPGKey){ 
        RSAPublicBCPGKey bcRSA = (RSAPublicBCPGKey)bcKey; 
        RSAPublicKeySpec specRSA = new RSAPublicKeySpec(bcRSA.getModulus(), bcRSA.getPublicExponent()); 
        PublicKey jceKey = KeyFactory.getInstance("RSA").generatePublic(specRSA); 
        // if you want to use the key in JCE, use jceKey 
        // if you want to write "X.509" (SPKI) DER format to a file: 
        Files.write(new File(outfile).toPath(), jceKey.getEncoded()); 
        // if you want to write in PEM, bouncycastle can do that 
        // or you can just do base64 and add BEGIN/END lines 
        return; // assume only one key; if need to handle multiple keys 
        // or select other than the first, specify more clearly 
       } 
      } 
     }  
    }