2016-10-04 7 views
0

pgp 형식으로 파일을 암호화해야합니다. 내 공개 키는 .asc 형식입니다.Java : .asc 파일에서 java.security.Key를 만드는 방법은 무엇입니까?

암호 init() 메서드는 전달할 공개 키가 필요합니다. 파일을 사용하여 키를 만드는 방법은 무엇입니까? 제 경우에는 .asc 파일입니다.

Cipher cipher; 
    Key publicKey = null; 

    try 
    { 
     cipher = Cipher.getInstance("RSA", "BC"); 




    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) { 
     String msg = "failed to create output stream"; 
     LOGGER.error(msg, e); 
     throw new RuntimeException(msg, e); 
    } 

    try { 
     publicKey = getPublicKey(publicKeyPath); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    try { 
     cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
    } catch (InvalidKeyException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return (new CipherOutputStream(outputStream, cipher)); 

나는 점점 오전 오류 : java.security.spec.InvalidKeySpecException : java.security.InvalidKeyException : 잘못된 키 형식 내의 getpublickey 방법처럼 보인다

(그러나 나는 생각한다, 나는이 없습니다

,691 : 파일이 공개 키 자체)

public static PublicKey getPublicKey(String filename) 
     throws Exception { 

     byte[] keyBytes = Files.readAllBytes(new File(filename).toPath()); 

     X509EncodedKeySpec spec = 
      new X509EncodedKeySpec(keyBytes); 
     KeyFactory kf = KeyFactory.getInstance("RSA"); 
     return kf.generatePublic(spec); 
     } 

Public_key.asc의 모양을 가지고로이 방법을 수행하는 여기

  -----BEGIN PGP PUBLIC KEY BLOCK----- 
      Version: Encryption Desktop 10.3.2 (Build 16127) 

      mQENBFYhXNoBCACgX/u03wm8cLqmTZiKGx6H/1ZUoBsfaDB2rdG2D8jYQzvaq4MA 
      hZWBEVhA2BGKrNI+a2SDhKGAY4OK7aUZVAVG1bfQNVdNe80TbEF8g/wO2FreYPkb 
      ojPtkwgyzsvb1BKwgRM1UMjkM5OWnhAPDhFDc39SFbmHLsXrURqFqJd9T3xzF6ty 

      ................................................................ 


      D4WXvHpPXCJcwCBe+/81ZpjxlrLkUu8bO79jxZdKcI5ZRpmIe/VPJoDUVKLvl9n3 
      ANvDJGdGcW3x6RyL9QOnoRDf6njimqcTm8UqImdLCz4TFdv94dvM4K0NOWuFdYal 
      E9Q+U0Q7aiaWn+Kt+OYpd6++m7wnJRH/q0H69LIR9v3Td3udzOaxv/gzXF1BFuAS 
      DQs6iA== 
      =ckOV 
      -----END PGP PUBLIC KEY BLOCK----- 

363,210이 키의 재산입니다 : 로버트에서

enter image description here

+1

당신은 사용할 수 없습니다 AES가있는 공개 키. AES는 128, 192 또는 256 비트의 임의 키가있는 대칭 암호입니다. 공개 키는 RSA, EC 또는 다른 비대칭 알고리즘입니다. 가스 탱크에 배터리를 떨어 뜨리는 것과 같습니다. – erickson

+1

X.509가 키 형식과 관련하여 PGP와 호환되지 않기 때문에 특별한 PGP 키 로더가 필요합니다. – Robert

+1

Bouncy Castle에서 PGP 기능을 사용하지 않는 이유는 무엇입니까? –

답변

1

회신 및 마르텐 Bodewes 갈 수있는 방법 중 하나입니다.

내 공개 키 .skr에서는 .asc 파일과 개인 키 (비밀 키 링)

에 있었다 나는 이런 식으로 구현 그리고 그것은 나를 위해 일한 :

   public static PublicKey getPublicKey(
        String filePath) 
        throws PGPException, NoSuchProviderException, FileNotFoundException, IOException 
       { 
        PGPPublicKey encKey = readPublicKey(new FileInputStream(filePath)); 
        return new JcaPGPKeyConverter().setProvider("BC").getPublicKey(encKey); 
       } 




       public static PrivateKey getPrivateKey( 
         InputStream in, char[]  passwd) 
         throws IOException, PGPException, NoSuchProviderException 
        { 
         in = PGPUtil.getDecoderStream(in); 

         PGPSecretKeyRingCollection  pgpSec = new PGPSecretKeyRingCollection(in); 

         // 
         // we just loop through the collection till we find a key suitable for encryption, in the real 
         // world you would probably want to be a bit smarter about this. 
         // 

         // 
         // iterate through the key rings. 
         // 
         Iterator<?> rIt = pgpSec.getKeyRings(); 

         while (rIt.hasNext()) 
         { 
          PGPSecretKeyRing kRing = (PGPSecretKeyRing)rIt.next();  
          Iterator<?>      kIt = kRing.getSecretKeys(); 

          while (kIt.hasNext()) 
          { 
           PGPSecretKey k = (PGPSecretKey)kIt.next(); 

           if (k != null) 
           { 
            PGPPrivateKey pk = k.extractPrivateKey(passwd, "BC"); 
            return new JcaPGPKeyConverter().setProvider("BC").getPrivateKey(pk); 
           } 
          } 
         } 

         throw new IllegalArgumentException("Can't find secured key in key ring."); 
        } 

       public static PGPPublicKey readPublicKey( 
         InputStream in) 
         throws IOException, PGPException 
        { 
         in = PGPUtil.getDecoderStream(in); 

         PGPPublicKeyRingCollection  pgpPub = new PGPPublicKeyRingCollection(in); 

         // 
         // we just loop through the collection till we find a key suitable for encryption, in the real 
         // world you would probably want to be a bit smarter about this. 
         // 

         // 
         // iterate through the key rings. 
         // 
         Iterator<?> rIt = pgpPub.getKeyRings(); 

         while (rIt.hasNext()) 
         { 
          PGPPublicKeyRing kRing = (PGPPublicKeyRing)rIt.next();  
          Iterator<?>      kIt = kRing.getPublicKeys(); 

          while (kIt.hasNext()) 
          { 
           PGPPublicKey k = (PGPPublicKey)kIt.next(); 

           if (k.isEncryptionKey()) 
           { 
            return k; 
           } 
          } 
         } 

         throw new IllegalArgumentException("Can't find encryption key in key ring."); 
        }