网站Logo nasico 博客

PGP 带签名加密

nasico
2
2023-06-21
public static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey) throws IOException, PGPException {
    Security.addProvider(new BouncyCastleProvider());

    out = new ArmoredOutputStream(out);

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);

    PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));

    comData.close();

    BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_256);
    dataEncryptor.setWithIntegrityPacket(true);
    dataEncryptor.setSecureRandom(new SecureRandom());

    PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
    encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));

    byte[] bytes = bOut.toByteArray();
    OutputStream cOut = encryptedDataGenerator.open(out, bytes.length);
    cOut.write(bytes);
    cOut.close();
    out.close();
}
动物装饰