- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 PKCS#7 进行签名和验证签名。我正在阅读《beginning cryptography with java》这本书。我已经编写了示例代码来签名和验证。当我尝试附加签名并将其写入文件,然后尝试验证时出现异常(下面给出异常)
我想知道我们如何将此签名数据写入文件?我是否还需要将 keystore 共享给第二个验证签名的人?
org.bouncycastle.cms.CMSException: message-digest attribute value does not match calculated value
at org.bouncycastle.cms.SignerInformation.doVerify(Unknown Source)
at org.bouncycastle.cms.SignerInformation.verify(Unknown Source)
at org.bouncycastle.cms.SignerInformation.verify(Unknown Source)
at com.inc.cms.test.bc.Test.isValidSignature(Test.java:150)
at com.inc.cms.test.bc.Test.verifyData(Test.java:120)
at com.inc.cms.test.bc.Test.main(Test.java:78)
非常感谢
我的代码如下
请帮我解决这个问题。非常感谢
`package com.inc.cms.test.bc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.CertPathBuilder;
import java.security.cert.CertStore;
import java.security.cert.Certificate;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.PKIXBuilderParameters;
import java.security.cert.PKIXCertPathBuilderResult;
import java.security.cert.TrustAnchor;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import javax.security.auth.x500.X500Principal;
import javax.security.auth.x500.X500PrivateCredential;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.cms.CMSProcessable;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.SignerId;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.x509.X509V1CertificateGenerator;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure;
import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure;
public class Test {
private static final char[] KEY_STORE_PASSWORD = "123456".toCharArray();
private static final long VALIDITY_PERIOD = 365 * 24 * 60 * 60 * 1000;
private static final char[] KEY_PASSWORD = "keyPassword".toCharArray();
public static String ROOT_ALIAS = "root";
public static String INTERMEDIATE_ALIAS = "intermediate";
public static String END_ENTITY_ALIAS = "end";
public static String PLAIN_TEXT = "Hello World!123";
public static void main(String[] args) {
try {
// CREATE KEY STORE
KeyStore keyStore = createKeyStore();
// STEP 1. SIGN
byte[] step1Data = PLAIN_TEXT.getBytes();
CMSSignedData cmsSignedData = signData(keyStore, step1Data);
new File("D:\\pkcs7\\encrypted-file.p7b");
FileOutputStream fileOuputStream = new FileOutputStream(
"D:\\pkcs7\\encrypted-file.p7b");
fileOuputStream.write(cmsSignedData.getEncoded());
fileOuputStream.flush();
fileOuputStream.close();
// STEP 2. READ ENCRYPTED DATA AND VERIFY SIGN AND DECRYPT IT
File file = new File("D:\\pkcs7\\encrypted-file.p7b");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] encryptedAndSignedByte = new byte[(int) file.length()];
fileInputStream.read(encryptedAndSignedByte);
fileInputStream.close();
cmsSignedData = new CMSSignedData(encryptedAndSignedByte);
if (verifyData(keyStore, cmsSignedData) == true) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static CMSSignedData signData(KeyStore keyStore,
byte[] encryptedData) throws Exception {
// GET THE PRIVATE KEY
PrivateKey key = (PrivateKey) keyStore.getKey(END_ENTITY_ALIAS,
KEY_PASSWORD);
Certificate[] chain = keyStore.getCertificateChain(END_ENTITY_ALIAS);
CertStore certsAndCRLs = CertStore.getInstance("Collection",
new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");
X509Certificate cert = (X509Certificate) chain[0];
// set up the generator
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA224);
gen.addCertificatesAndCRLs(certsAndCRLs);
// create the signed-data object
CMSProcessable data = new CMSProcessableByteArray(encryptedData);
CMSSignedData signed = gen.generate(data, "BC");
// recreate
signed = new CMSSignedData(data, signed.getEncoded());
// ContentInfo conInf = signed.getContentInfo();
// CMSProcessable sigContent = signed.getSignedContent();
return signed;
}
private static boolean verifyData(KeyStore keyStore, CMSSignedData signed)
throws Exception {
// verification step
X509Certificate rootCert = (X509Certificate) keyStore
.getCertificate(ROOT_ALIAS);
if (isValidSignature(signed, rootCert)) {
System.out.println("verification succeeded");
return true;
} else {
System.out.println("verification failed");
}
return false;
}
/**
* Take a CMS SignedData message and a trust anchor and determine if the
* message is signed with a valid signature from a end entity entity
* certificate recognized by the trust anchor rootCert.
*/
private static boolean isValidSignature(CMSSignedData signedData,
X509Certificate rootCert) throws Exception {
boolean[] bArr = new boolean[2];
bArr[0] = true;
CertStore certsAndCRLs = signedData.getCertificatesAndCRLs(
"Collection", "BC");
SignerInformationStore signers = signedData.getSignerInfos();
Iterator it = signers.getSigners().iterator();
if (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
SignerId signerConstraints = signer.getSID();
signerConstraints.setKeyUsage(bArr);
PKIXCertPathBuilderResult result = buildPath(rootCert,
signer.getSID(), certsAndCRLs);
return signer.verify(result.getPublicKey(), "BC");
}
return false;
}
/**
* Build a path using the given root as the trust anchor, and the passed in
* end constraints and certificate store.
* <p>
* Note: the path is built with revocation checking turned off.
*/
public static PKIXCertPathBuilderResult buildPath(X509Certificate rootCert,
X509CertSelector endConstraints, CertStore certsAndCRLs)
throws Exception {
CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
PKIXBuilderParameters buildParams = new PKIXBuilderParameters(
Collections.singleton(new TrustAnchor(rootCert, null)),
endConstraints);
buildParams.addCertStore(certsAndCRLs);
buildParams.setRevocationEnabled(false);
return (PKIXCertPathBuilderResult) builder.build(buildParams);
}
/**
* Create a KeyStore containing the a private credential with certificate
* chain and a trust anchor.
*/
public static KeyStore createKeyStore() throws Exception {
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.load(null, null);
X500PrivateCredential rootCredential = createRootCredential();
X500PrivateCredential interCredential = createIntermediateCredential(
rootCredential.getPrivateKey(), rootCredential.getCertificate());
X500PrivateCredential endCredential = createEndEntityCredential(
interCredential.getPrivateKey(),
interCredential.getCertificate());
keyStore.setCertificateEntry(rootCredential.getAlias(),
rootCredential.getCertificate());
keyStore.setKeyEntry(
endCredential.getAlias(),
endCredential.getPrivateKey(),
KEY_PASSWORD,
new Certificate[] { endCredential.getCertificate(),
interCredential.getCertificate(),
rootCredential.getCertificate() });
keyStore.store(new FileOutputStream("d:\\pkcs7\\KeyStore.jks"),
KEY_STORE_PASSWORD);
return keyStore;
}
/**
* Create a random 1024 bit RSA key pair
*/
public static KeyPair generateRSAKeyPair() throws Exception {
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
kpGen.initialize(1024, new SecureRandom());
return kpGen.generateKeyPair();
}
/**
* Generate a sample V1 certificate to use as a CA root certificate
*/
public static X509Certificate generateCertificate(KeyPair pair)
throws Exception {
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X500Principal("CN=Test CA Certificate"));
certGen.setNotBefore(new Date(System.currentTimeMillis()
- VALIDITY_PERIOD));
certGen.setNotAfter(new Date(System.currentTimeMillis()
+ VALIDITY_PERIOD));
certGen.setSubjectDN(new X500Principal("CN=Test CA Certificate"));
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}
/**
* Generate a sample V1 certificate to use as a CA root certificate
*/
public static X509Certificate generateRootCert(KeyPair pair)
throws Exception {
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X500Principal("CN=Test CA Certificate"));
certGen.setNotBefore(new Date(System.currentTimeMillis()
- VALIDITY_PERIOD));
certGen.setNotAfter(new Date(System.currentTimeMillis()
+ VALIDITY_PERIOD));
certGen.setSubjectDN(new X500Principal("CN=Test CA Certificate"));
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}
/**
* Generate a sample V3 certificate to use as an end entity certificate
*/
public static X509Certificate generateEndEntityCert(PublicKey entityKey,
PrivateKey caKey, X509Certificate caCert) throws Exception {
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(caCert.getSubjectX500Principal());
certGen.setNotBefore(new Date(System.currentTimeMillis()
- VALIDITY_PERIOD));
certGen.setNotAfter(new Date(System.currentTimeMillis()
+ VALIDITY_PERIOD));
certGen.setSubjectDN(new X500Principal("CN=Test End Certificate"));
certGen.setPublicKey(entityKey);
certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
new AuthorityKeyIdentifierStructure(caCert));
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
new SubjectKeyIdentifierStructure(entityKey));
certGen.addExtension(X509Extensions.BasicConstraints, true,
new BasicConstraints(false));
certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(
KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
return certGen.generateX509Certificate(caKey, "BC");
}
/**
* Generate a X500PrivateCredential for the root entity.
*/
public static X500PrivateCredential createRootCredential() throws Exception {
KeyPair rootPair = generateRSAKeyPair();
X509Certificate rootCert = generateRootCert(rootPair);
return new X500PrivateCredential(rootCert, rootPair.getPrivate(),
ROOT_ALIAS);
}
/**
* Generate a X500PrivateCredential for the intermediate entity.
*/
public static X500PrivateCredential createIntermediateCredential(
PrivateKey caKey, X509Certificate caCert) throws Exception {
KeyPair interPair = generateRSAKeyPair();
X509Certificate interCert = generateIntermediateCert(
interPair.getPublic(), caKey, caCert);
return new X500PrivateCredential(interCert, interPair.getPrivate(),
INTERMEDIATE_ALIAS);
}
/**
* Generate a X500PrivateCredential for the end entity.
*/
public static X500PrivateCredential createEndEntityCredential(
PrivateKey caKey, X509Certificate caCert) throws Exception {
KeyPair endPair = generateRSAKeyPair();
X509Certificate endCert = generateEndEntityCert(endPair.getPublic(),
caKey, caCert);
return new X500PrivateCredential(endCert, endPair.getPrivate(),
END_ENTITY_ALIAS);
}
/**
* Generate a sample V3 certificate to use as an intermediate CA certificate
*/
public static X509Certificate generateIntermediateCert(PublicKey intKey,
PrivateKey caKey, X509Certificate caCert) throws Exception {
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(caCert.getSubjectX500Principal());
certGen.setNotBefore(new Date(System.currentTimeMillis()));
certGen.setNotAfter(new Date(System.currentTimeMillis()
+ VALIDITY_PERIOD));
certGen.setSubjectDN(new X500Principal(
"CN=Test Intermediate Certificate"));
certGen.setPublicKey(intKey);
certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
new AuthorityKeyIdentifierStructure(caCert));
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
new SubjectKeyIdentifierStructure(intKey));
certGen.addExtension(X509Extensions.BasicConstraints, true,
new BasicConstraints(0));
certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(
KeyUsage.digitalSignature | KeyUsage.keyCertSign
| KeyUsage.cRLSign));
return certGen.generateX509Certificate(caKey, "BC");
}
}
最佳答案
试试这个:
public static void main(String[] args)throws Exception
{
String password = "123456";
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Hex format : " + sb.toString());
//convert the byte to hex format method 2
StringBuffer hexString = new StringBuffer();
for (int i=0;i<byteData.length;i++) {
String hex=Integer.toHexString(0xff & byteData[i]);
if(hex.length()==1) hexString.append('0');
hexString.append(hex);
}
System.out.println("Hex format : " + hexString.toString());
}
关于java - PKCS#7 登录并验证签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11133014/
常用的 PKCS 标准有什么用:PKCS#7、PKCS#10 和 PKCS#12? 最佳答案 PKCS#7 允许您使用 X.509 证书对通用数据进行签名和加密。 PKCS#7 格式也可用于存储一个或
我想知道当使用 AES-128-CBC 时,openssl 如何处理可被 8 个字节整除的消息。 openssl 如何检测到没有要删除的填充(PKCS#5/PKCS#7)?特别是当消息以 ASCII
我正在阅读 PKCS 11 文档,但我无法清楚地理解 key 的 CKA_SENSITIVE 属性是什么意思。 更常见的是:我在哪里可以阅读属性描述? 最佳答案 引自 PKCS#11 spec v2.
我想寻求有关使用 cryptography.hazmat.primitives.padding.PKCS7 的帮助Python 类。 解密后,我得到字符串45394700000019770808080
我知道 PKCS#7 = 证书 + 可选原始数据 + PKCS#1 格式的签名 我需要从 PKCS#7 签名中提取 PKCS#1 如何在 C# 中执行此操作。我可以用充气城堡来做这个吗,这是我的实现I
我希望能够使用带有 aws golang SDK 的 AWS SNS 发送 iOS APNS 推送通知。我按照以下说明创建了一个 p12 文件:https://support-aws.s3.amazo
关闭。这个问题需要更多focused .它目前不接受答案。 想改善这个问题吗?更新问题,使其仅关注一个问题 editing this post . 2年前关闭。 Improve this questi
我正在开发一个移动应用程序,它必须验证它收到的一些签名。我拥有我需要的一切——输入数据、公钥和签名。但有一个问题。我使用方法 SHA256withRSA 进行签名验证,其中包含以下几行代码来验证签名:
我有一个 PKCS#5 加密的 PKCS#8 RSA 私钥存储在一个磁盘文件中(最初由 SSLPlus 生成,大约在 1997 年),例如: -----BEGIN ENCRYPTED PRIVATE
是否可以将 PKCS#8 编码的 RSA 私钥转换为 PKCS#1?我知道这可以通过 openssl 轻松完成,但是可以用 Java 完成吗? 最佳答案 使用 BouncyCaSTLe 1.50 Pr
我正在为 Android 实现 Jscep。最初,我尝试了 Jscep for java,效果很好。现在在 Android 中,我使用 SpongyCaSTLe 而不是 BouncyCaSTLe。现在
我正在尝试在 SafeNet HSM 中生成一个 RSA key 对。我为私钥和公钥复制了 PKCS11 中指定的示例模板。当我生成 key 对时,一切正常。但是,当我为私钥指定以下属性值时,C_Ge
密码学在信息安全中扮演着至关重要的角色。为了保护敏感信息、数字身份和网络通信的安全性,密码设备(如硬件安全模块HSM)与应用程序之间的安全通信和互操作性变得至关重要。PKCS#11(Public-K
这玩意折腾了一天,有个老外的代码,公钥用了PKCS#1,私钥用了PKCS#8。调用了不同的API,而我的全是生成的PKCS#8,后面查阅了大量资料和长时间调试程序,才发现了问题,在此记录下。 用Ope
PKCS#12是一种将私钥与其对应的 X.509 证书合并为标准化的单一文件格式的便捷方式。然而,该规范于 1999 年由 RSALabs 发布,并且仅使用 RC4、RC2 和 TripleDES 进
我正在尝试使用 PKCS#7 进行签名和验证签名。我正在阅读《beginning cryptography with java》这本书。我已经编写了示例代码来签名和验证。当我尝试附加签名并将其写入文件
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 想改进这个问题?将问题更新为 on-topic对于堆栈溢出。 4年前关闭。 Improve this qu
使用java加密、签名、解密、验证签名需要遵循哪些步骤? 使用 PKCS#7 算法, java keystore 有什么用?关于 PKCS#7。 最佳答案 第 1 步 使用 keytool 实用程序生
我在 iPhone 上使用这个 OpenSSL 代码生成一个 PKCS#12 文件,给定证书/私钥的一些数据。我能够验证此 PKCS#12 在 OpenSSL 上是否可解析,因为当我在代码中检查它时它
我实际上正在研究一个应该从 PKCS7 mime 加密消息中提取 RecipientInfo 的函数。我想这样做的原因是,我想获取邮件加密的所有邮件地址(或至少是 keyids/指纹)。 嗯 - 我尝
我是一名优秀的程序员,十分优秀!