【发布时间】:2019-08-25 16:44:45
【问题描述】:
我正在尝试使用带有 USB 令牌中存在的私钥的 Bouncy Castle fips 库生成签名 CSR。
目前充气城堡不提供将签名字节(使用 USB 令牌生成)附加到 pkcs10certificationRequest 的选项。
如何使用充气城堡库来实现这一点。??
我正在使用 PKCS10CertificationRequest 对象来生成签名 CSR,它期望 ContentSigner 对象作为输入,所以我通过实现方法创建了自己的 contentsigner 1. 获取签名()。 2. 获取输出流()。 3. getalgorithmidentifier().
getsignature 函数调用 PKCS11 库调用以使用 x500Name 和公钥作为输入生成签名,并使用令牌中存在的私钥对输入数据进行签名。
使用此流程,我可以生成签名的 CSR,但是当我尝试使用 isvalid() 函数验证生成的签名 CSR 时,它会抛出错误“无效签名”
使用以下代码生成签名的 CSR 使用带有 PKCS11 库的充气城堡:
在哪里
publicKeyInfo is a public key retrieved from usb token.
signingPrivKey is a handle for the private key present in usb token.
CertificationRequestInfo certificateRequestInfo = new CertificationRequestInfo(subject, publicKeyInfo, new DERSet());
ContentSigner contentSigner = new ContentSigner() {
@Override
public byte[] getSignature()
{
try
{
PrivateKey signingPrivKey = null;
RSAPrivateKey templateForSignKey = new RSAPrivateKey();
templateForSignKey.getId().setByteArrayValue(id);
session.findObjectsInit(templateForSignKey);
Object[] privKeyObjects = session.findObjects(1);
if (privKeyObjects.length > 0)
{
signingPrivKey = (PrivateKey) privKeyObjects[0];
}
session.findObjectsFinal();
ByteArrayInputStream dataInputStream = new ByteArrayInputStream(certificateRequestInfo.getEncoded());
MessageDigest digestEngine = MessageDigest.getInstance("SHA-256", "BCFIPS");
Mechanism signatureMechanism = Mechanism.get(PKCS11Constants.CKM_RSA_PKCS);
//Initialize for signing
session.signInit(signatureMechanism, signingPrivKey);
byte[] dataBuffer = new byte[1024];
int bytesRead;
// feed all data from the input stream to the message digest
while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0)
{
digestEngine.update(dataBuffer, 0, bytesRead);
}
byte[] digest = digestEngine.digest();
byte[] signatureValue = session.sign(digest);
return signatureValue;
}
catch (TokenException e)
{
setMsg(e.getMessage());
}
catch (NoSuchAlgorithmException e)
{
setMsg(e.getMessage());
}
catch (FileNotFoundException e)
{
setMsg(e.getMessage());
}
catch (IOException e)
{
setMsg(e.getMessage());
}
return null;
}
@Override
public OutputStream getOutputStream()
{
return null;
}
@Override
public AlgorithmIdentifier getAlgorithmIdentifier()
{
AlgorithmIdentifier algorithmIdentifier = new DefaultSignatureAlgorithmIdentifierFinder().find(hashingAlgo);
return algorithmIdentifier;
}
};
AlgorithmIdentifier algorithmId = contentSigner.getAlgorithmIdentifier();
byte[] signData = contentSigner.getSignature();
DERBitString derBitStr = new DERBitString(signData);
CertificationRequest certReq = new CertificationRequest(certificateRequestInfo, algorithmId, derBitStr);
PKCS10CertificationRequest pkcs10Req = new PKCS10CertificationRequest(certReq);
【问题讨论】:
标签: java bouncycastle