jjzjj

java - 使用充气城堡创建 Thunderbird 可用的公共(public) PGP key

coder 2024-03-31 原文

我创建了公共(public)和私有(private) PGP使用 key org.bouncycastle.openpgp.PGPKeyRingGenerator .进行 GregS 建议的更改后,公钥是 .asc文件,私钥是 .skr文件。我首先需要将公钥分发给 Thunderbird 用户,然后再分发给 Outlook 和其他电子邮件客户端的用户。我读了 these instructions for receiving a public key in thunderbird ,但说明只指定了一个 .asc没有指定 .asc 的内容/结构的扩展名文件。

如何设置以便我下面的(修改过的?)代码创建一个公钥,Thunderbird 的远程用户可以使用它来发送加密的电子邮件,然后可以通过我的私钥解密,私钥也是由(修改过的?)代码创建的以下? 接受的答案将包括分步说明,不仅用于对下面的代码进行任何必要的更改,还用于设置每个远程 Thunderbird 用户以使用下面生成的公钥发送可以由我的应用程序中的私钥,由下面的(已修改?)代码创建。

这是我的 key 生成代码的初稿:

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Date;

import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.bouncycastle.bcpg.sig.Features;
import org.bouncycastle.bcpg.sig.KeyFlags;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPKeyRingGenerator;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator;
import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor;
import org.bouncycastle.openpgp.operator.PGPDigestCalculator;
import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyEncryptorBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider;
import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair;  

public class RSAGen {
    public static void main(String args[]) throws Exception {
        char pass[] = {'h', 'e', 'l', 'l', 'o'};
        PGPKeyRingGenerator krgen = generateKeyRingGenerator("alice@example.com", pass);

        // Generate public key ring, dump to file.
        PGPPublicKeyRing pkr = krgen.generatePublicKeyRing();
        ArmoredOutputStream pubout = new ArmoredOutputStream(new BufferedOutputStream(new FileOutputStream("/home/user/dummy.asc")));
        pkr.encode(pubout);
        pubout.close();

        // Generate private key, dump to file.
        PGPSecretKeyRing skr = krgen.generateSecretKeyRing();
        BufferedOutputStream secout = new BufferedOutputStream(new FileOutputStream("/home/user/dummy.skr"));
        skr.encode(secout);
        secout.close();
    }

    public final static PGPKeyRingGenerator generateKeyRingGenerator(String id, char[] pass) throws Exception{
        return generateKeyRingGenerator(id, pass, 0xc0); 
    }

    // Note: s2kcount is a number between 0 and 0xff that controls the number of times to iterate the password hash before use. More
    // iterations are useful against offline attacks, as it takes more time to check each password. The actual number of iterations is
    // rather complex, and also depends on the hash function in use. Refer to Section 3.7.1.3 in rfc4880.txt. Bigger numbers give
    // you more iterations.  As a rough rule of thumb, when using SHA256 as the hashing function, 0x10 gives you about 64
    // iterations, 0x20 about 128, 0x30 about 256 and so on till 0xf0, or about 1 million iterations. The maximum you can go to is
    // 0xff, or about 2 million iterations.  I'll use 0xc0 as a default -- about 130,000 iterations.

    public final static PGPKeyRingGenerator generateKeyRingGenerator(String id, char[] pass, int s2kcount) throws Exception {
        // This object generates individual key-pairs.
        RSAKeyPairGenerator  kpg = new RSAKeyPairGenerator();

        // Boilerplate RSA parameters, no need to change anything
        // except for the RSA key-size (2048). You can use whatever key-size makes sense for you -- 4096, etc.
        kpg.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), new SecureRandom(), 2048, 12));

        // First create the master (signing) key with the generator.
        PGPKeyPair rsakp_sign = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, kpg.generateKeyPair(), new Date());
        // Then an encryption subkey.
        PGPKeyPair rsakp_enc = new BcPGPKeyPair(PGPPublicKey.RSA_ENCRYPT, kpg.generateKeyPair(), new Date());

        // Add a self-signature on the id
        PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator();

        // Add signed metadata on the signature.
        // 1) Declare its purpose
        signhashgen.setKeyFlags(false, KeyFlags.SIGN_DATA|KeyFlags.CERTIFY_OTHER);
        // 2) Set preferences for secondary crypto algorithms to use when sending messages to this key.
        signhashgen.setPreferredSymmetricAlgorithms
            (false, new int[] {
                SymmetricKeyAlgorithmTags.AES_256,
                SymmetricKeyAlgorithmTags.AES_192,
                SymmetricKeyAlgorithmTags.AES_128
            });
        signhashgen.setPreferredHashAlgorithms
            (false, new int[] {
                HashAlgorithmTags.SHA256,
                HashAlgorithmTags.SHA1,
                HashAlgorithmTags.SHA384,
                HashAlgorithmTags.SHA512,
                HashAlgorithmTags.SHA224,
            });
        // 3) Request senders add additional checksums to the message (useful when verifying unsigned messages.)
        signhashgen.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION);

        // Create a signature on the encryption subkey.
        PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator();
        // Add metadata to declare its purpose
        enchashgen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS|KeyFlags.ENCRYPT_STORAGE);

        // Objects used to encrypt the secret key.
        PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1);
        PGPDigestCalculator sha256Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA256);

        // bcpg 1.48 exposes this API that includes s2kcount. Earlier versions use a default of 0x60.
        PBESecretKeyEncryptor pske = (new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha256Calc, s2kcount)).build(pass);

        // Finally, create the keyring itself. The constructor takes parameters that allow it to generate the self signature.
        PGPKeyRingGenerator keyRingGen =
            new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, rsakp_sign,
         id, sha1Calc, signhashgen.generate(), null,
             new BcPGPContentSignerBuilder(rsakp_sign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1), pske);

        // Add our encryption subkey, together with its signature.
        keyRingGen.addSubKey(rsakp_enc, enchashgen.generate(), null);
        return keyRingGen;
    }
}

当我运行上面的代码来生成 .asc文件,然后尝试导入 .asc文件到 Thunderbird,我得到以下错误屏幕:



请注意,我没有在 CentOS 7 机器上安装 GnuPG。

另外,你可以在自己的机器上轻松重现这个问题,因为 Thunderbird 是免费的。 You can download thunderbird for free using this link .或者,在我的 CentOS 7 上机器,我用 yum install thunderbird 下载了 Thunderbird .您可以通过将以下内容添加到您的 pom.xml 来下载充气城堡。 :
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcpg-jdk15on</artifactId>
    <version>1.51</version>
</dependency>

编辑#1:

为了解决JRichardSnape 的问题,我发现maven 也必须自动下载org.bouncycastle.crypto库,因为它是 bcpg-jdk15on 的依赖项. JRichardSnape 是正确的 RSAKeyGenerationParameters RSAKeyPairGenerator 不在 bcpg-jdk15on.jar手动下载。 (注意:链接中的版本可能不是最新的。)但是,这两个类都在自动 Maven 下载中,该下载是由来自 pom.xml 的单个依赖项片段产生的。如上所示。 我这样说是因为没有其他 bouncycastle我的 pom.xml 中的依赖项.我正在使用 Java 7。

Eclipse 将导入的两个类描述为:
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;  

我添加了所有 import来自 RSAGen.java 的声明到我上面 OP 中的代码段。我认为问题可能与需要 key 的名称/签名有关。

谷歌搜索此错误会导致以下链接,其中包括:

Convert userId to UTF8 before generating signature #96
non-ascii characters in Name field #92
Unable to import PGP certificate into Keychain

编辑#2

根据@JRichardSnape 的建议,我尝试了 Enigmail->Key management ->File ->Import keys from file .这导致出现以下对话框,这似乎表明,在导入 key 时,未对 key 进行签名。因此,似乎没有与 .asc 相关联的姓名或电子邮件地址。导入的文件。之后,该 key 也不会出现在 EnigMail 的 key 列表中。



编辑#3

使用 gpg --gen-key ,我能够让 CentOS 7 终端创建一个 key 对,包括一个公钥,我能够成功地将它导入到 Thunderbird,这样 Thunderbird 现在可以将终端 gpg 生成的公钥与预期的电子邮件收件人相关联。但是,当我采取所有步骤使用公钥从 Thunderbird 发送加密电子邮件时,电子邮件及其附件仍然未加密。我将带有公钥的加密电子邮件从远程 Thunderbird 发送到具有私钥的服务器所采取的步骤是 described in this SuperUser posting .

鉴于 gpg --gen-key似乎工作,目前主要的遗留问题,似乎是这个赏金问题的雷鸟部分。我已经在上一段的 SuperUser 问题中发布了解决 Thunderbird 部分的很多进展。您的回答对回答这个问题也大有帮助。

编辑#4

我仍然无法获得 BouncyCastle -创建了导入 Thunderbird 的 key 。但是,当我使用在 CentOS 7 上创建的 key 时终端使用 gpg --gen-key ,我能够完成以下步骤:
1.) I configured my Thunderbird to manage another (second) 
    email account I have not been using.  
2.) I then created a gpg key for that second account and 
    configured encryption for that second account in Thunderbird.  
3.) I sent an encrypted email containing an attachment from the  
    first Thunderbird account to the second Thunderbird account.
4.) I was able to see that the attachment remained encrypted in  
    the second account's inbox until I used the recipient key's  
    passphrase to decrypt it.

我的 CentOS 7当我从本编辑中描述的相同“第一个”Thunderbird 帐户向服务器发送电子邮件时,服务器仍在生成未加密的附件。我试图确定这是否是由于 dovecot 中的某些“自动解密”引起的/postfix/mailx/gpgCentOS 7服务器,或者是否由于 Thunderbird 发送器中的某些设置。我正在研究这个。

最佳答案

我将尝试一一解决这些问题:

Java bouncycaSTLe key 环生成

Java 代码确实有效并生成了一个可用的 key 环对。我已经用不同的电子邮件和不同的密码对其进行了测试,没有任何问题。我让第 3 方使用公钥向我发送了一封电子邮件,并使用此 Java 代码生成的私钥成功解密了它。 key 已与以下组合一起使用

  • Windows 8 上的 Thunderbird (31.4.0) + Enigmail (1.7.2) + gpg (Gpg4win)
  • ubuntu 14.10 上的 Thunderbird + Enigmail(使用 xfer 桌面管理器)

  • 然而

    OP 发现导入 key 时出现问题,失败意味着 CentOS / Thunderbird / pgp 中没有用户 ID组合。同样,导入失败,错误提示 Windows / Outlook / Kleopatra 上没有用户 ID。插件(尽管问题特别引用了 Thunderbird,但已测试)。

    我无法重现该错误 - 强烈怀疑这是由于 GNU PG 中的配置差异或版本差异造成的。我的设置为 gpg --version 显示以下内容
    gpg (GnuPG) 2.0.26 (Gpg4win 2.2.3)
    libgcrypt 1.6.2
    

    直接用 gpg 测试 Java 生成的 key

    您可以使用 java 代码生成 key ,转到命令行并执行
    gpg --import dummy.asc
    

    然后测试是通过执行
    gpg --edit-key alice@example.com
    

    通过键入 check 检查它是否具有用户 ID在 gpg>迅速的。示例输出:
    uid  alice@example.com
    sig!3        14AEE94A 2015-02-05  [self-signature]
    

    如果这有效 - 您已经消除了 key 导入的 gpg 问题 - 检查 Thunderbird/Enigmail 版本。

    使用雷鸟

    我的评论建议通过 Enigmail->Key management ->File ->Import keys from file 导入 key 似乎已经解决了大部分问题。结合 this related question来自 super 用户的 OP。

    另请注意 - Enigmail 的 key 管理对话框中有一个“生成”选项。如果不需要 Java 生成,这可用于生成 key 对 - 据我所知,它与通过 gpg 直接生成基本相同。

    使用 Thunderbird 的剩余问题似乎是对加密缺乏信心,因为消息以纯文本形式出现在 OP 的服务器上(似乎 key 将用于服务器/客户端组合,客户端将加密的电子邮件发送到服务器)。

    为了确保消息确实被加密了 - 我建议更改 Enigmail 设置:
  • Enigmail -> Preference -> Sending tab
  • 选择 "Manual encryption settings"
  • 选择 "Always""confirm before sending"盒子

  • 然后,您将在发送之前看到加密邮件和一个确认框。

    我不能说如何停止您的服务器自动解密收到的邮件,因为这取决于您的服务器配置,最好作为单独的问题提出,很可能在 superuserserverfault StackExchange 站点。

    测试 PGP 电子邮件

    您也可以考虑遵循 the Enigmail tutorial 的建议并将加密邮件发送至

    Adele, the "Friendly OpenPGP Email Robot". Adele accepts OpenPGP messages and replies in an explanatory way to any kind of OpenPGP messages.



    地址是adele <at> gnupp <dot> de

    关于java - 使用充气城堡创建 Thunderbird 可用的公共(public) PGP key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28245669/

    有关java - 使用充气城堡创建 Thunderbird 可用的公共(public) PGP key的更多相关文章

    1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

      我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

    2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

      我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

    3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

      类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

    4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

      很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

    5. ruby - 在 Ruby 中使用匿名模块 - 2

      假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

    6. ruby - 如何在 Ruby 中顺序创建 PI - 2

      出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

    7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

      我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

    8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

      关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

    9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

      我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

    10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

      我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

    随机推荐