搜索

263.3. 使用 PGPDataFormat 加密

download PDF

以下示例使用 popular PGP 格式通过 Bouncy Castle Java 库 加密/解密文件:

以下示例执行签名 + 加密,然后签名验证 + 解密。它对签名和加密使用相同的密钥环,但您可以明显使用不同的密钥:

或使用 Spring:

263.3.1. 要使用前面的示例,您需要以下内容

  • 包含用于加密数据的公钥的公共密钥环文件
  • 私有密钥环文件,其中包含用于解密数据的密钥
  • 密钥环密码

263.3.2. 管理密钥环

若要管理密钥环,我使用命令行工具,我发现这是管理密钥的最简单方法。如果您希望通过这个方法进行此操作,还提供 http://www.bouncycastle.org/java.html 中的 Java 库。

在 linux 中安装命令行工具

apt-get install gnupg

创建密钥环,输入安全密码

gpg --gen-key

如果您需要导入其他人的公钥,以便您可以为其加密文件。

gpg --import <filename.key

以下文件现在应存在,可用于运行示例

ls -l ~/.gnupg/pubring.gpg ~/.gnupg/secring.gpg

[[crypto-PGPDecrypting/VerifyingofMessagesEncrypted/SignedbyDifferentPrivate/PublicKeys] PGP Decrypting/Verifying of Messages Encrypted/Signed by different # Private/Public Keys

Camel 2.12.2 开始。

PGP Data Formater 可以解密/验证由不同公钥加密或由不同私钥签名的消息。只需在 secret keyring 中提供对应的私钥、公共密钥环中的对应公钥,以及密码短语访问器中的密码短语。

Map<String, String> userId2Passphrase = new HashMap<String, String>(2);
// add passphrases of several private keys whose corresponding public keys have been used to encrypt the messages
userId2Passphrase.put("UserIdOfKey1","passphrase1"); // you must specify the exact User ID!
userId2Passphrase.put("UserIdOfKey2","passphrase2");
PGPPassphraseAccessor passphraseAccessor = new PGPPassphraseAccessorDefault(userId2Passphrase);

PGPDataFormat pgpVerifyAndDecrypt = new PGPDataFormat();
pgpVerifyAndDecrypt.setPassphraseAccessor(passphraseAccessor);
// the method getSecKeyRing() provides the secret keyring as byte array containing the private keys
pgpVerifyAndDecrypt.setEncryptionKeyRing(getSecKeyRing()); // alternatively you can use setKeyFileName(keyfileName)
// the method getPublicKeyRing() provides the public keyring as byte array containing the public keys
pgpVerifyAndDecrypt.setSignatureKeyRing((getPublicKeyRing());  // alternatively you can use setSignatureKeyFileName(signatgureKeyfileName)
// it is not necessary to specify the encryption or signer  User Id

from("direct:start")
         ...
        .unmarshal(pgpVerifyAndDecrypt) // can decrypt/verify messages encrypted/signed by different private/public keys
        ...
  • 功能对于支持密钥交换特别有用。如果要交换私钥以进行解密,您可以接受点以旧或新的公钥加密的时间消息。或者,如果发送者希望交换签名人私钥,您可在一段时间内接受旧签名者密钥。
  • 技术背景:PGP 加密的数据包含用于加密数据的公钥的密钥 ID。此密钥 ID 可用于查找机密密钥环中的私钥,以解密数据。相同的机制也用于查找验证签名的公钥。因此,您不再必须为 unmarshaling 指定用户 ID。
Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.