Bouncy Castle CMS公钥加密

时间:2018-04-25 21:44:24

标签: java encryption bouncycastle public-key-encryption

我跟随此示例:http://www.baeldung.com/java-bouncy-castle

我有几个问题:

public static byte[] encryptData(byte[] data,
  X509Certificate encryptionCertificate)
  throws CertificateEncodingException, CMSException, IOException {

    byte[] encryptedData = null;
    if (null != data && null != encryptionCertificate) {
        CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator
          = new CMSEnvelopedDataGenerator();

        JceKeyTransRecipientInfoGenerator jceKey 
          = new JceKeyTransRecipientInfoGenerator(encryptionCertificate);
        cmsEnvelopedDataGenerator.addRecipientInfoGenerator(transKeyGen);
        CMSTypedData msg = new CMSProcessableByteArray(data);
        OutputEncryptor encryptor
          = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC)
          .setProvider("BC").build();
        CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator
          .generate(msg,encryptor);
        encryptedData = cmsEnvelopedData.getEncoded();
    }
    return encryptedData;
}

将此应用于我的真实世界场景,我只有收件人的RSA公钥而不是整个X509Certificate。我捅了一下,但我不确定如何才能做到这一点。有可能吗?

另一件事是我看到JceCMSEncryptorBuilder采用ASN1ObjectIdentifier。我们目前正在使用类似的内容:

KeyGenerator cryptKeyGenerator = KeyGenerator.getInstance("AES", "BC");
cryptKeyGenerator.init(256);
Key encryptionKey = cryptKeyGenerator.generateKey();
Cipher symmetricCipher = Cipher.getInstance("AES/CTS/NoPadding", "BC");
symmetricCipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(ivBytes));

在CMSAlgorithm类中,我没有看到任何CTS选项。我错过了什么或有没有办法继续使用CTS?

1 个答案:

答案 0 :(得分:1)

  

我只有收件人的RSA公钥,而不是整个X509Certificate

KeyTransRecipientInfo structure of CMS EnvelopedData可以使用SubjectKeyIdentifier值sometimes present in the X.509/PKIX certificate as an extensionBouncy has an overloaded ctor for this case。由于您没有证书,如果收件人将使用证书,或者尝试不同的猜测,您必须找出用于计算证书中值的方法(s?)直到找到一个有效的,或者如果你控制收件人,只需选择它(他们)将接受的一些值。

org.bouncycastle.cert.X509ExtensionUtils及其两个子类提供了计算两种标准方案的方法,但我发现它们比直接方法更方便。

  

我们目前正在使用... AES / CTS / NoPadding ...而在CMSAlgorithm课程中,我没有看到任何CTS选项

它不仅仅是CMSAlgorithm中的内容。有两个相关因素:

  • CMS / PKCS7 EnvelopedData中使用的任何特定密码(以JCA术语,转换)必须由OID和条件参数标识

  • 发件人和收件人或所有收件人必须支持用于给定邮件的密码。

org.bouncycastle.cms.CMSAlgorithm只是一个方便的密码汇编和其他一些事项,如密钥协议,它们都有标准化的OID并由BC实现,后者实际上由org.bouncycastle.cms.jcajce.EnvelopedDataHelperthe bc-native equivalent控制。因为您可以看到支持的块密码仅支持CBC模式。 (两者都支持RC4,但作为流密码,它不使用任何模式。加上RC4现在非常不受欢迎。)

我不记得曾经在CTS模式下看到过密码的任何标准化OID。如果那是对的,那么您必须分配一个,并且由于没有其他人会实现该OID,因此您的消息将无法与任何人互操作。如果您可以找到您的同行实施的标准OID(或至少AlgId),那么对于BC,您必须创建符合(接口)OutputEncryptor的自己的类,这不是'如果您查看上面的源代码,那么您可以使用基础密码的提供程序或bc-native实现。

相关问题