2016-11-27 3 views
0

공개 키를 공개 키 형식으로 변환하는 방법이 X.509 키 형식으로 변환되는지 알고있는 사람이 있습니까? 아마도 Bouncy Castle이나 익숙한 것을 사용했을까요?PGP 공개 키 변환

지금 당장 X509 공개 키를 X509EncodedKeySpecs 및 PublicKey를 사용하여 디코딩 할 수 있기 때문에 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 
       } 
      } 
     }  
    }