JAVA 下的 pgp加密解密示例

 

main类

 

public class Main
{
  public static void main(String[] args)
    throws Exception
  {
    try
    {

        encryptFile("公钥", "待加密文件路径", "加密结果路径");
    }
    catch (Exception e)
    {
      e.printStackTrace();
      showHelp();
    }
  }
  
  private static void decryptFile(String secretasc, String password, String decryFile, String decryedFile)
    throws IOException, NoSuchProviderException
  {
    Security.addProvider(new BouncyCastleProvider());
    OpenPGPUtil.decryptFile(decryFile, secretasc, password.toCharArray(), decryedFile);
  }
  
  private static void encryptFile(String publicasc, String encrypFile, String outFile)
    throws NoSuchProviderException, IOException, PGPException
  {
    Security.addProvider(new BouncyCastleProvider());
    OpenPGPUtil.encryptFile(outFile, encrypFile, publicasc, false, true);
  }
  

}
 

 

 

 


public class OpenPGPUtil
{
  public static void decryptFile(String inputFileName, String keyFileName, char[] passwd, String defaultFileName)
    throws IOException, NoSuchProviderException
  {
    InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
    decryptFile(in, keyIn, passwd, defaultFileName);
    keyIn.close();
    in.close();
  }
  
  public static void decryptFile(InputStream in, InputStream keyIn, char[] passwd, String defaultFileName)
    throws IOException, NoSuchProviderException
  {
    in = PGPUtil.getDecoderStream(in);
    try
    {
      JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
      
      Object o = pgpF.nextObject();
      PGPEncryptedDataList enc;
      PGPEncryptedDataList enc;
      if ((o instanceof PGPEncryptedDataList)) {
        enc = (PGPEncryptedDataList)o;
      } else {
        enc = (PGPEncryptedDataList)pgpF.nextObject();
      }
      Iterator it = enc.getEncryptedDataObjects();
      PGPPrivateKey sKey = null;
      PGPPublicKeyEncryptedData pbe = null;
      PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
        PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator());
      while ((sKey == null) && (it.hasNext()))
      {
        pbe = (PGPPublicKeyEncryptedData)it.next();
        sKey = PGPExampleUtil.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
      }
      if (sKey == null) {
        throw new IllegalArgumentException("secret key for message not found.");
      }
      InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
      
      JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);
      
      Object message = plainFact.nextObject();
      for (;;)
      {
        if ((message instanceof PGPCompressedData))
        {
          PGPCompressedData cData = (PGPCompressedData)message;
          JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
          message = pgpFact.nextObject();
        }
        if ((message instanceof PGPLiteralData))
        {
          PGPLiteralData ld = (PGPLiteralData)message;
          String outFileName = defaultFileName;
          InputStream unc = ld.getInputStream();
          OutputStream fOut = new BufferedOutputStream(new FileOutputStream(outFileName));
          Streams.pipeAll(unc, fOut);
          fOut.close();
          break;
        }
        if ((message instanceof PGPOnePassSignatureList)) {
          System.out.println("encrypted message contains a signed message - not literal data.");
        } else if ((message instanceof PGPSignatureList)) {
          System.out.println("encrypted message contains a signed message - not literal data.");
        } else {
          throw new PGPException("message is not a simple encrypted file - type unknown.");
        }
        message = plainFact.nextObject();
      }
      if (pbe.isIntegrityProtected())
      {
        if (!pbe.verify()) {
          System.err.println("message failed integrity check");
        } else {
          System.err.println("message integrity check passed");
        }
      }
      else {
        System.err.println("no message integrity check");
      }
    }
    catch (PGPException e)
    {
      System.err.println(e);
      if (e.getUnderlyingException() != null) {
        e.getUnderlyingException().printStackTrace();
      }
    }
  }
  
  public static void encryptFile(String outputFileName, String inputFileName, String encKeyFileName, boolean armor, boolean withIntegrityCheck)
    throws IOException, NoSuchProviderException, PGPException
  {
    OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFileName));
    PGPPublicKey encKey = PGPExampleUtil.readPublicKey(encKeyFileName);
    encryptFile(out, inputFileName, encKey, armor, withIntegrityCheck);
    out.close();
  }
  
  public static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, boolean armor, boolean withIntegrityCheck)
    throws IOException, NoSuchProviderException
  {
    if (armor) {
      out = new ArmoredOutputStream(out);
    }
    try
    {
      byte[] bytes = PGPExampleUtil.compressFile(fileName, 1);
      PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
        new JcePGPDataEncryptorBuilder(3).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC"));
      
      encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC"));
      
      OutputStream cOut = encGen.open(out, bytes.length);
      
      cOut.write(bytes);
      cOut.close();
      if (armor) {
        out.close();
      }
    }
    catch (PGPException e)
    {
      System.err.println(e);
      if (e.getUnderlyingException() != null) {
        e.getUnderlyingException().printStackTrace();
      }
    }
  }
}
 

 

 

 


class PGPExampleUtil
{
  static byte[] compressFile(String var0, int var1)
    throws IOException
  {
    ByteArrayOutputStream var2 = new ByteArrayOutputStream();
    PGPCompressedDataGenerator var3 = new PGPCompressedDataGenerator(var1);
    PGPUtil.writeFileToLiteralData(var3.open(var2), 'b', new File(var0));
    var3.close();
    return var2.toByteArray();
  }
  
  static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection var0, long var1, char[] var3)
    throws PGPException, NoSuchProviderException
  {
    PGPSecretKey var4 = var0.getSecretKey(var1);
    return var4 == null ? null : var4.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(var3));
  }
  
  static PGPPublicKey readPublicKey(String var0)
    throws IOException, PGPException
  {
    BufferedInputStream var1 = new BufferedInputStream(new FileInputStream(var0));
    PGPPublicKey var2 = readPublicKey(var1);
    var1.close();
    return var2;
  }
  
  static PGPPublicKey readPublicKey(InputStream var0)
    throws IOException, PGPException
  {
    PGPPublicKeyRingCollection var1 = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(var0), new JcaKeyFingerprintCalculator());
    Iterator var2 = var1.getKeyRings();
    Iterator var4;
    for (; var2.hasNext(); var4.hasNext())
    {
      PGPPublicKeyRing var3 = (PGPPublicKeyRing)var2.next();
      var4 = var3.getPublicKeys();
      
      continue;
      PGPPublicKey var5 = (PGPPublicKey)var4.next();
      if (var5.isEncryptionKey()) {
        return var5;
      }
    }
    throw new IllegalArgumentException("Can't find encryption key in key ring.");
  }
  
  static PGPSecretKey readSecretKey(String var0)
    throws IOException, PGPException
  {
    BufferedInputStream var1 = new BufferedInputStream(new FileInputStream(var0));
    PGPSecretKey var2 = readSecretKey(var1);
    var1.close();
    return var2;
  }
  
  static PGPSecretKey readSecretKey(InputStream var0)
    throws IOException, PGPException
  {
    PGPSecretKeyRingCollection var1 = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(var0), new JcaKeyFingerprintCalculator());
    Iterator var2 = var1.getKeyRings();
    Iterator var4;
    for (; var2.hasNext(); var4.hasNext())
    {
      PGPSecretKeyRing var3 = (PGPSecretKeyRing)var2.next();
      var4 = var3.getSecretKeys();
      
      continue;
      PGPSecretKey var5 = (PGPSecretKey)var4.next();
      if (var5.isSigningKey()) {
        return var5;
      }
    }
    throw new IllegalArgumentException("Can't find signing key in key ring.");
  }
}
 

 

 

 

 


public class PgpKeyUtil
{
  private static PGPKeyBundle complexPublicKey;
  private static PGPKeyBundle complexPrivateKey;
  
  public static void genKey(String recipientName, String Passphrase, String publicAscAddr, String secretAscAddr)
  {
    Security.addProvider(new CryptixCrypto());
    
    Security.addProvider(new CryptixOpenPGP());
    
    generateComplexKey(recipientName, Passphrase);
    
    writeKeys(publicAscAddr, secretAscAddr);
  }
  
  public static void generateComplexKey(String recipientName, String Passphrase)
  {
    SecureRandom sr = new SecureRandom();
    try
    {
      KeyBundleFactory kbf = KeyBundleFactory.getInstance("OpenPGP");
      complexPublicKey = (PGPKeyBundle)kbf.generateEmptyKeyBundle();
      complexPrivateKey = (PGPKeyBundle)kbf.generateEmptyKeyBundle();
      
      KeyPairGenerator kpg = KeyPairGenerator.getInstance("OpenPGP/Signing/DSA");
      kpg.initialize(1024, sr);
      
      KeyPair kp = kpg.generateKeyPair();
      PublicKey pubkey = kp.getPublic();
      PrivateKey privkey = kp.getPrivate();
      
      PrincipalBuilder princbuilder = 
        PrincipalBuilder.getInstance("OpenPGP/UserID");
      
      Principal userid = princbuilder.build(recipientName);
      
      CertificateBuilder certbuilder = 
        CertificateBuilder.getInstance("OpenPGP/Self");
      Certificate cert = 
        certbuilder.build(pubkey, userid, privkey, sr);
      
      complexPublicKey.addCertificate(cert);
      complexPrivateKey.addCertificate(cert);
      
      complexPrivateKey.addPrivateKey(privkey, pubkey, 
        Passphrase.toCharArray(), sr);
    }
    catch (Exception e)
    {

      e.printStackTrace();
    }
    KeyPairGenerator kpg = null;
    try
    {
      kpg = KeyPairGenerator.getInstance("OpenPGP/Encryption/ElGamal");
    }
    catch (NoSuchAlgorithmException nsae)
    {
     
      nsae.printStackTrace();
    }
    kpg.initialize(1024, sr);
    KeyPair kp = kpg.generateKeyPair();
    
    PublicKey pubsubkey = kp.getPublic();
    PrivateKey privsubkey = kp.getPrivate();
    
    PublicKey pubmainkey = null;
    PrivateKey privmainkey = null;
    try
    {
      pubmainkey = (PublicKey)complexPrivateKey.getPublicKeys().next();
      privmainkey = complexPrivateKey.getPrivateKey(pubmainkey, 
        Passphrase.toCharArray());
    }
    catch (UnrecoverableKeyException uke)
    {
      uke.printStackTrace();
    }
    try
    {
      complexPublicKey.addPublicSubKey(pubsubkey, privmainkey);
    }
    catch (KeyBundleException kbe)
    {
      System.err.println("Adding the subkey and/or generating the blinding signature failed.");
      
      kbe.printStackTrace();
    }
    try
    {
      complexPrivateKey.addPublicSubKey(pubsubkey, complexPublicKey);
    }
    catch (KeyBundleException kbe)
    {
      kbe.printStackTrace();
    }
    try
    {
      complexPrivateKey.addPrivateSubKey(privsubkey, pubsubkey, 
        Passphrase.toCharArray(), sr);
    }
    catch (KeyBundleException kbe)
    {
      kbe.printStackTrace();
    }
    try
    {
      PrincipalBuilder princbuilder = 
        PrincipalBuilder.getInstance("OpenPGP/UserID");
      Principal userid = princbuilder.build(recipientName);
      
      CertificateBuilder certbuilder = 
        CertificateBuilder.getInstance("OpenPGP/Self");
      Certificate cert = certbuilder.build(pubmainkey, userid, 
        privmainkey, sr);
      
      complexPublicKey.addCertificate(cert);
      complexPrivateKey.addCertificate(cert);
    }
    catch (NoSuchAlgorithmException nsae)
    {
      nsae.printStackTrace();
    }
    catch (PrincipalException pe)
    {
      pe.printStackTrace();
    }
    catch (CertificateException ce)
    {
      ce.printStackTrace();
    }
    catch (KeyBundleException kbe)
    {
      kbe.printStackTrace();
    }
  }
  
  /* Error */
  public static void writeKeys(String publicAscAddr, String secretAscAddr)
  {

  }
  
  public static void main(String[] args)
    throws Exception
  {
    genKey("aaaaaaaa", "123456", "公约路径", "私钥路径");
  }
}

 

 

 

 

 

 

public class PgpTools
{
  public void decryptFile(String secretasc, String password, String decryFile, String decryedFile)
    throws IOException, NoSuchProviderException
  {
    Security.addProvider(new BouncyCastleProvider());
    OpenPGPUtil.decryptFile(decryFile, secretasc, password.toCharArray(), decryedFile);
  }
  
  public void encryptFile(String publicasc, String encrypFile, String outFile)
    throws NoSuchProviderException, IOException, PGPException
  {
    Security.addProvider(new BouncyCastleProvider());
    OpenPGPUtil.encryptFile(outFile, encrypFile, publicasc, false, true);
  }
}

 

 

 

你可能感兴趣的:(java)