在Java中使用.pfx证书和pkcs7签署数据

时间:2020-05-25 10:43:30

标签: java digital-signature pkcs#7

我有一个.pfx证书和密码,现在我想使用.pfx对数据进行数字签名,然后生成pkcs7编码的字符串。

据我所知,我编写了以下代码。请让我告诉我这段代码有什么问题:

byte[] origMsg;
String msg = "1004546640";
byte[] base64Encoded = Base64.encodeBase64(msg.getBytes());
Charset ascii = Charset.forName("US-ASCII");
String asciiEncoded = new String(base64Encoded, ascii);
//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 = "1004546640".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();
String st = Base64.getEncoder().encodeToString(encodedPKCS7);
System.out.println(st);

0 个答案:

没有答案