ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

使用Java将外部PKCS1字节数组和证书添加到CMS容器

2019-11-22 01:03:34  阅读:330  来源: 互联网

标签:digital-signature pkcs7 bouncycastle java


我们拥有创建PKCS1 v2.1数字签名的客户端应用程序(Applets和Silverlight).由于未将原始内容下载到客户端,因此将数字签名创建为PKCS1,因此仅将内容的哈希发送到客户端以节省带宽.

我们正在尝试创建PKCS7 / CMS容器服务器端based on the information from this post

>阅读证书并以X509证书类型加载
>将PKCS1签名读取为base64并作为字节数组加载
>实例化新的ASN1ObjectIdentifier并设置PKCS1 OID(1.2.840.113549.1.1)
>使用asn1对象和signare字节[]作为参数创建新的CMSTypedData CMSProcessableByteArray
>创建新的CMSSignedGenerator并添加证书
>使用CMSTypedData类型创建新的CMSSignedData作为分离的签名

但是,转到第5步和第6步时,事情就会中断,因为BC CMSSignedGenerator和CMSSignedData类不支持添加没有私钥的签署者:

CMS创建:

    // Add BC to environment
    Security.addProvider(new BouncyCastleProvider());

    // Read certificate and convert to X509Certificate
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    Path certPath = Paths.get("C:\\MyCertificate.cer");
    byte[] certData = Files.readAllBytes(certPath);
    InputStream in = new ByteArrayInputStream(certData);
    X509Certificate cert = (X509Certificate)certFactory.generateCertificate(in);

    // Add signer certificates to List and add them to store
    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(cert);
    Store certs = new JcaCertStore(certList);

    // Get signature in Base64, decode and convert to byte array
    // Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
    String signatureBase64 = "gjTbsD0vSOi6nMlRVbpTLRQ5j+g2h8iEH1DgQx93PDBuwzWT47urKxMAS+75dAhQrkreLt9TGZaDN85e5xEpIF12mK1G+AgCNc370I1bjxOvUU67IVxHkZ+IX8kzSiD2uNuQtk3IrwUqyL30TIo+LDAXmY1AQVZwXAaOYG4bXxI=";
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] signatureByte = decoder.decodeBuffer(signatureBase64);

    // Instantiate new ANS1ObjectIdentifier to identify PKCS1 signature
    ASN1ObjectIdentifier asn1OidPkcs1 = new ASN1ObjectIdentifier("1.2.840.113549.1.1");

    // Table generator
    /*AttributeTable attrT = new AttributeTable();
    SimpleAttributeTableGenerator sAttrTGen = new SimpleAttributeTableGenerator();*/

    // Instantiate new CMSProcessable object
    CMSTypedData msg = new CMSProcessableByteArray(asn1OidPkcs1, signatureByte);

    // Instantiate new CMSSignedDataGenerator object
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    // ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").s
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(msg, false);


    // BASE64Encoder encoder = new BASE64Encoder();
    new File("C:\\MyCMS.p7s");
    FileOutputStream fileOuputStream = new FileOutputStream("C:\\Users\\gregwerner\\Documents\\Archivos\\miFirma.p7s"); 
    fileOuputStream.write(sigData.getEncoded());
    fileOuputStream.flush();
    fileOuputStream.close();

}

关于如何完成CMS容器的任何想法?也许使用AttributeTable为时间戳等添加了多个OID,但这似乎也不起作用.

解决方法:

在查看此参考项目https://code.google.com/p/j4ops/之后,我找到了答案.尽管该指南特别针对使用iText的PDF(使用加密操作的BC:http://itextpdf.com/book/digitalsignatures20130304.pdf)处理PDF,但它也是一个很大的帮助.窍门是将签名操作委托给外部提供程序(PKCS11 ,PKCS12等),例如,通过实现使用sign(byte [] toEncrypt)方法的Signer接口.这样,可以设置提供程序,然后仅调用sign方法,并保留有关如何对提供程序本身进行签名的实现详细信息.

Bouncy Castle使用CMSSignedDataGenerator类和SignerInf内部类来分别构建CMS容器和签名者信息.因此,诀窍是建立一个不需要私钥的SignerInf对象,因为sign()操作应委托给提供者.私钥甚至可能不可用,特别是在使用智能卡时.此外,在签名哈希和构建CMS容器时,需要考虑需要添加为签名属性和/或未签名属性的信息.因此,这些是解决问题的基本步骤:

// Build the items to encrypt, objects for method parameters would be obtained previously.
byte[] toEncrypt = externalSignerInfoGenerator.getCmsBytesToSign(hash, 
            signingTime, 
            PKCSObjectIdentifiers.data, 
            x509Cert, 
            timeStampToken, 
            ocsp);
// The externalSignerInfoGenerator.getCmsBytesToSign is a method from a re implemention of the 
// SignerInf inner class from CMSSignedDataGenerator and is used to get a byte array from an 
// org.bouncycastle.asn1.ASN1EncodableVector. To build the vector one should add attributes to
// their corresponding OID's using the org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers interface,
// for example:
ASN1EncodableVector signedAttrVector = buildSignedAttributes (hash, signingTime, contentType,
x509Cert, ocspResp);
// This would call the buildSignedAttributes method to build the signed attributes vector
ASN1EncodableVector signedAttrVector = new ASN1EncodableVector();
// Add CMS attributes
signedAttrVector.add (new Attribute(CMSAttributes.contentType, new DERSet (contentType)));
signedAttrVector.add (new Attribute (CMSAttributes.signingTime, new DERSet(new Time (signingTime))));
signedAttrVector.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(hash))));
// Not all attributes are considered in BC's CMSAttributes interface, therefore one would have to add 
// an additional step:
signedAttrVector.add(buildOcspResponseAttribute(ocspResp));
// This method would call buildOcspResponseAttribute to add the object as a PKCSObjectIdentifier
protected Attribute buildOcspResponseAttribute (byte[] ocspResp) throws IOException, CMSException {
    return new Attribute (PKCSObjectIdentifiers.id_aa_ets_revocationRefs, 
    new DERSet(DERUtil.readDERObject(ocspResp)));
}  

// Call sign method from provider, such as PKCS11, PKCS12, etc.
byte [] signature = getSignProvider().sign(toEncrypt);
// Now build standard org.bouncycastle.cms.SignerInfoGenerator with hash, signed data 
// and certificate to add to CMS, create attached or detached signature
// create signed envelope
CMSSignedData envdata = externalCMSSignedDataGenerator.generate(false);                
byte[] enveloped = envdata.getEncoded();

标签:digital-signature,pkcs7,bouncycastle,java
来源: https://codeday.me/bug/20191122/2055969.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有