Java 中的 PKCS7 编码,没有像 BouncyCastle 等外部库

信息安全 爪哇 电子签名 编码
2021-09-02 23:01:45

我正在对 CMS/PKCS#7 消息(类似于 C# SignedCms)进行签名和编码。

我有来自密钥库、rsa 私钥、
ContentInfo 的 x509certificate。内容类型是“oidPkcs7Data”。

我不太明白我接下来应该做什么。

我想:

  1. 生成签名并签署 ContentInfo 数据
    签名签名 = Signature.getInstance("MD5withRSA");
    签名.initSign(rsaPrivateKeyFromStore); 
    签名.update(contentInfo.getData());
    签名数据 = 签名.sign();
  1. 编码签名数据+签名。
    PKCS7 pkcs7 = 新 PKCS7(签名数据);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    pkcs7.encodeSignedData(baos);

但我得到了例外

sun.security.pkcs.ParsingException:无法解析编码字节
    在 sun.security.pkcs.PKCS7.(PKCS7.java:94)

显然我做错了。

我也想在没有 BouncyCastle 或 Classpth 或像这些的 smth 的情况下这样做。

是否可以只使用 sun.security.* 类?我使用java 1.5。

我是 DigitalSignature 世界的新人,感谢您提供任何帮助或建议。

UPD

我生成了自己的证书并尝试用它对数据进行签名。

.Net 代码

        X509Certificate2 certificate = new X509Certificate2("X:\\mypfxstore.pfx", "123");
        String text = "text";
        ContentInfo contentInfo = new ContentInfo(System.Text.Encoding.UTF8.GetBytes(text));
        SignedCms cms = new SignedCms(contentInfo, false);
        CmsSigner signer = new CmsSigner(certificate);
        signer.IncludeOption = X509IncludeOption.None;
        signer.DigestAlgorithm = new Oid("SHA1");
        cms.ComputeSignature(signer, false);
        byte[] signature = cms.Encode();
        print(signature);

.Java 代码

    char[] password = "123".toCharArray();
    String text = "text";

    FileInputStream fis = new FileInputStream("X:\\mypfxstore.pfx");
    KeyStore ks = KeyStore.getInstance("pkcs12");
    ks.load(fis, password);

    String alias = ks.aliases().nextElement();
    PrivateKey pKey = (PrivateKey)ks.getKey(alias, password);
    X509Certificate c = (X509Certificate)ks.getCertificate(alias);

    //Data to sign
    byte[] dataToSign = text.getBytes("UTF-8");
    //compute signature:
    Signature signature = Signature.getInstance("SHA1WithRSA");
    signature.initSign(pKey);
    signature.update(dataToSign);
    byte[] signedData = signature.sign();

    //load X500Name
    X500Name xName      = X500Name.asX500Name(c.getSubjectX500Principal());
    //load serial number
    BigInteger serial   = c.getSerialNumber();
    //laod digest algorithm
    AlgorithmId digestAlgorithmId = new AlgorithmId(AlgorithmId.SHA_oid);
    //load signing algorithm
    AlgorithmId signAlgorithmId = new AlgorithmId(AlgorithmId.RSAEncryption_oid);

    //Create SignerInfo:
    SignerInfo sInfo = new SignerInfo(xName, serial, digestAlgorithmId, signAlgorithmId, signedData);

    //Create ContentInfo:
    ContentInfo cInfo = new ContentInfo(ContentInfo.DIGESTED_DATA_OID, new DerValue(DerValue.tag_OctetString, dataToSign));

    //Create PKCS7 Signed data
    PKCS7 p7 = new PKCS7(new AlgorithmId[] { digestAlgorithmId }, cInfo,
            new java.security.cert.X509Certificate[] { /*cert,*/ },
            new SignerInfo[] { sInfo });

    //Write PKCS7 to bYteArray
    ByteArrayOutputStream bOut = new DerOutputStream();
    p7.encodeSignedData(bOut);
    byte[] encoded = bOut.toByteArray();

    print(encoded);

Java 输出

length=264
3082010406092A864886F70D010702A081F63081F3020101310B300906052B0E03021A0500
301306092A864886F70D0 -> 10705A <- 0060404746578743181CB3081C8020101302630123110300E06
035504031307436F6D70616E790210FCAF9B5224FB4B9F4000B5127D881E2E300906052B0E0302
1A0500300D06092A864886F70D0101010500048180636ADD9F7E218AF3CBC5A75FA2076A53BE49
03DC864E87EBA3C1EE594FAACAFE93CA6F3410D847AC0C0ACB9FD88EC9CF6B00379FA9AD256C86
7204ED81E3FA2F8F492109FF87E81398B7B489B00A35914A2B51919DAAEC2BA87CEFB5AF52294E
2448B5B150D50A39BA0471A9AA1EA2B38A4E23BBA56E029842459F0D5BA3D511

.Net 输出

length=264
3082010406092A864886F70D010702A081F63081F3020101310B300906052B0E03021A0500
301306092A864886F70D0 -> 10701A <- 0060404746578743181CB3081C8020101302630123110300E06
035504031307436F6D70616E790210FCAF9B5224FB4B9F4000B5127D881E2E300906052B0E0302
1A0500300D06092A864886F70D0101010500048180636ADD9F7E218AF3CBC5A75FA2076A53BE49
03DC864E87EBA3C1EE594FAACAFE93CA6F3410D847AC0C0ACB9FD88EC9CF6B00379FA9AD256C86
7204ED81E3FA2F8F492109FF87E81398B7B489B00A35914A2B51919DAAEC2BA87CEFB5AF52294E
2448B5B150D50A39BA0471A9AA1EA2B38A4E23BBA56E029842459F0D5BA3D511

证书示例示例

1个回答
package test.pkcs7;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import sun.security.pkcs.ContentInfo;
import sun.security.pkcs.PKCS7;
import sun.security.pkcs.SignerInfo;
import sun.security.util.DerOutputStream;
import sun.security.util.DerValue;
import sun.security.x509.AlgorithmId;
import sun.security.x509.X500Name;

public class GenPKCS {

    static final String STORENAME = "c:/fileName.p12";
    static final String STOREPASS = "password";

    public static void main(String[] args) throws Exception{

        //First load the keystore object by providing the p12 file path
        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        //replace testPass with the p12 password/pin
        clientStore.load(new FileInputStream(STORENAME), STOREPASS.toCharArray());

        Enumeration<String> aliases = clientStore.aliases();
        String aliaz = "";
        while(aliases.hasMoreElements()){
            aliaz = aliases.nextElement();
            if(clientStore.isKeyEntry(aliaz)){
                break;
            }
        }
        X509Certificate c = (X509Certificate)clientStore.getCertificate(aliaz);

        //Data to sign
        byte[] dataToSign = "SigmaWorld".getBytes();
        //compute signature:
        Signature signature = Signature.getInstance("Sha1WithRSA");
        signature.initSign((PrivateKey)clientStore.getKey(aliaz, STOREPASS.toCharArray()));
        signature.update(dataToSign);
        byte[] signedData = signature.sign();

        //load X500Name
        X500Name xName      = X500Name.asX500Name(c.getSubjectX500Principal());
        //load serial number
        BigInteger serial   = c.getSerialNumber();
        //laod digest algorithm
        AlgorithmId digestAlgorithmId = new AlgorithmId(AlgorithmId.SHA_oid);
        //load signing algorithm
        AlgorithmId signAlgorithmId = new AlgorithmId(AlgorithmId.RSAEncryption_oid);

        //Create SignerInfo:
        SignerInfo sInfo = new SignerInfo(xName, serial, digestAlgorithmId, signAlgorithmId, signedData);
        //Create ContentInfo:
        ContentInfo cInfo = new ContentInfo(ContentInfo.DIGESTED_DATA_OID, new DerValue(DerValue.tag_OctetString, dataToSign));
        //Create PKCS7 Signed data
        PKCS7 p7 = new PKCS7(new AlgorithmId[] { digestAlgorithmId }, cInfo,
                new java.security.cert.X509Certificate[] { c },
                new SignerInfo[] { sInfo });
        //Write PKCS7 to bYteArray
        ByteArrayOutputStream bOut = new DerOutputStream();
        p7.encodeSignedData(bOut);
        byte[] encodedPKCS7 = bOut.toByteArray();
    }
}

将在 Java 代码中进行以下更改以使输出类似于 .NET:

//Create ContentInfo:
ContentInfo cInfo = new ContentInfo(ContentInfo.DIGESTED_DATA_OID, new DerValue(DerValue.tag_OctetString, dataToSign));

改成

//Create ContentInfo:
ContentInfo cInfo = new ContentInfo(ContentInfo.DATA_OID, new DerValue(DerValue.tag_OctetString, dataToSign));