【问题标题】:When and why decorate OutputStream with ArmoredOutputStream when using BouncyCastle使用 BouncyCastle 时何时以及为何使用 ArmoredOutputStream 装饰 OutputStream
【发布时间】:2014-08-13 02:01:27
【问题描述】:

我对 BouncyCastle 和 pgp 还是很陌生。我在互联网上看到了很多文章和示例。几乎每个加密样本都包含下面的代码

if (armor) 
        out = new ArmoredOutputStream(out);

看来我的本地测试通过了盔甲和无盔甲。我四处搜索,但发现很少有用,ArmoredOutputStream 的 javadoc 只显示这是基本输出流。

那么有什么区别,什么时候用呢?

完整的代码示例:

public static void encryptFile(String decryptedFilePath,
        String encryptedFilePath,
        String encKeyPath,
        boolean armor,
        boolean withIntegrityCheck)            
        throws Exception{

    OutputStream out = new FileOutputStream(encryptedFilePath);
    FileInputStream pubKey = new FileInputStream(encKeyPath);
    PGPPublicKey encKey = readPublicKeyFromCollection2(pubKey);
    Security.addProvider(new BouncyCastleProvider());

    if (armor) 
        out = new ArmoredOutputStream(out);

    // Init encrypted data generator
    PGPEncryptedDataGenerator encryptedDataGenerator =
            new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, withIntegrityCheck, new SecureRandom(),"BC");

    encryptedDataGenerator.addMethod(encKey);


    OutputStream encryptedOut = encryptedDataGenerator.open(out, new byte[BUFFER_SIZE]);

    // Init compression  
    PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
    OutputStream compressedOut = compressedDataGenerator.open(encryptedOut);  

    PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
    OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, decryptedFilePath, new Date(), new byte[BUFFER_SIZE]);
    FileInputStream inputFileStream = new FileInputStream(decryptedFilePath);
    byte[] buf = new byte[BUFFER_SIZE];  
    int len;
    while((len = inputFileStream.read(buf))>0){
        literalOut.write(buf,0,len);
    }

    literalOut.close();
    literalDataGenerator.close();

    compressedOut.close();
    compressedDataGenerator.close();
    encryptedOut.close();
    encryptedDataGenerator.close();
    inputFileStream.close();
    out.close();

}
}

【问题讨论】:

    标签: java encryption bouncycastle pgp openpgp


    【解决方案1】:

    ArmoredOutputStream 使用类似于Base64 的编码,以便将二进制不可打印字节转换为文本友好的内容。如果您想通过电子邮件发送数据,或者在网站或其他文本媒体上发布数据,您可以这样做。

    它在安全性方面没有任何区别。不过有a slight expansion of the message size。选择实际上仅取决于您要对输出做什么。

    【讨论】:

      【解决方案2】:

      ASCII Armor 是一个通用术语,表示二进制数据表示为纯 ASCII 文本。从技术上讲,ascii-armor 二进制数据有很多方法,但在与密码学相关的领域,the PEM format 很普遍(也可以在 serverfault 上查看this and related questions)。

      PEM 基本上是一个 Base64 编码的二进制数据,包装在 -----BEGIN SOMETHING----------END SOMETHING----- 分隔符中,以及一组额外的标头,其中可以包含有关二进制内容的一些元信息。

      【讨论】:

        猜你喜欢
        • 2017-12-29
        • 1970-01-01
        • 2020-07-22
        • 1970-01-01
        • 2021-07-19
        • 1970-01-01
        • 2023-03-15
        • 2010-12-05
        相关资源
        最近更新 更多