java 数字信封_【Java密码学】使用Bouncy Castle生成数字签名、数字信封

java 数字信封_【Java密码学】使用Bouncy Castle生成数字签名、数字信封importjava.io.FileInputStream;importjava.io.InputStream;importjava.security.KeyStore;importjava.security.PrivateKey;importjava.security.Provider;importjava.security.Security;importjava.security.cert.C…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

importjava.io.FileInputStream;importjava.io.InputStream;importjava.security.KeyStore;importjava.security.PrivateKey;importjava.security.Provider;importjava.security.Security;importjava.security.cert.Certificate;importjava.security.cert.CertificateFactory;importjava.security.cert.X509Certificate;importjava.util.ArrayList;importjava.util.Collection;importjava.util.Iterator;importjava.util.List;importorg.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;importorg.bouncycastle.cert.X509CertificateHolder;importorg.bouncycastle.cert.jcajce.JcaCertStore;importorg.bouncycastle.cms.CMSEnvelopedData;importorg.bouncycastle.cms.CMSEnvelopedDataGenerator;importorg.bouncycastle.cms.CMSProcessableByteArray;importorg.bouncycastle.cms.CMSSignedData;importorg.bouncycastle.cms.CMSSignedDataGenerator;importorg.bouncycastle.cms.CMSTypedData;importorg.bouncycastle.cms.RecipientInformation;importorg.bouncycastle.cms.RecipientInformationStore;importorg.bouncycastle.cms.SignerInformation;importorg.bouncycastle.cms.SignerInformationStore;importorg.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;importorg.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;importorg.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder;importorg.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;importorg.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator;importorg.bouncycastle.jce.provider.BouncyCastleProvider;importorg.bouncycastle.operator.ContentSigner;importorg.bouncycastle.operator.jcajce.JcaContentSignerBuilder;importorg.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;importorg.bouncycastle.util.Store;importorg.bouncycastle.util.encoders.Base64;public classMessageUtil {private String ksType = “PKCS12”;/*** 生成数字签名

*@paramsrcMsg 源信息

*@paramcharSet 字符编码

*@paramcertPath 证书路径

*@paramcertPwd 证书密码

*@return

*/

public byte[] signMessage(String srcMsg, String charSet, String certPath, String certPwd) {

String priKeyName= null;char passphrase[] =certPwd.toCharArray();try{

Provider provider= newBouncyCastleProvider();//添加BouncyCastle作为安全提供

Security.addProvider(provider);//加载证书

KeyStore ks =KeyStore.getInstance(ksType);

ks.load(newFileInputStream(certPath), passphrase);if(ks.aliases().hasMoreElements()) {

priKeyName=ks.aliases().nextElement();

}

Certificate cert=(Certificate) ks.getCertificate(priKeyName);//获取私钥

PrivateKey prikey =(PrivateKey) ks.getKey(priKeyName, passphrase);

X509Certificate cerx509=(X509Certificate) cert;

List certList = new ArrayList();

certList.add(cerx509);

CMSTypedData msg= (CMSTypedData) newCMSProcessableByteArray(

srcMsg.getBytes(charSet));

Store certs= newJcaCertStore(certList);

CMSSignedDataGenerator gen= newCMSSignedDataGenerator();

ContentSigner sha1Signer= newJcaContentSignerBuilder(“SHA1withRSA”).setProvider(“BC”).build(prikey);

gen.addSignerInfoGenerator(newJcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(“BC”)

.build()).build(sha1Signer, cerx509));

gen.addCertificates(certs);

CMSSignedData sigData= gen.generate(msg, true);returnBase64.encode(sigData.getEncoded());

}catch(Exception e) {

e.printStackTrace();return null;

}

}/*** 验证数字签名

*@paramsignedData

*@return

*/

public boolean signedDataVerify(byte[] signedData) {boolean verifyRet = true;try{//新建PKCS#7签名数据处理对象

CMSSignedData sign = newCMSSignedData(signedData);//添加BouncyCastle作为安全提供

Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());//获得证书信息

Store certs =sign.getCertificates();//获得签名者信息

SignerInformationStore signers =sign.getSignerInfos();

Collection c=signers.getSigners();

Iterator it=c.iterator();//当有多个签名者信息时需要全部验证

while(it.hasNext()) {

SignerInformation signer=(SignerInformation) it.next();//证书链

Collection certCollection =certs.getMatches(signer.getSID());

Iterator certIt=certCollection.iterator();

X509CertificateHolder cert=(X509CertificateHolder) certIt

.next();//验证数字签名

if (signer.verify(newJcaSimpleSignerInfoVerifierBuilder()

.setProvider(“BC”).build(cert))) {

verifyRet= true;

}else{

verifyRet= false;

}

}

}catch(Exception e) {

verifyRet= false;

e.printStackTrace();

System.out.println(“验证数字签名失败”);

}returnverifyRet;

}/*** 加密数据

*@paramsrcMsg 源信息

*@paramcertPath 证书路径

*@paramcharSet 字符编码

*@return*@throwsException*/

public String envelopeMessage(String srcMsg, String certPath, String charSet) throwsException {

CertificateFactory certificatefactory;

X509Certificate cert;//使用公钥对对称密钥进行加密//若此处不加参数 “BC” 会报异常:CertificateException –

certificatefactory = CertificateFactory.getInstance(“X.509”, “BC”);//读取.crt文件;你可以读取绝对路径文件下的crt,返回一个InputStream(或其子类)即可。

InputStream bais = newFileInputStream(certPath);

cert=(X509Certificate) certificatefactory.generateCertificate(bais);//添加数字信封

CMSTypedData msg = newCMSProcessableByteArray(srcMsg.getBytes(charSet));

CMSEnvelopedDataGenerator edGen= newCMSEnvelopedDataGenerator();

edGen.addRecipientInfoGenerator(newJceKeyTransRecipientInfoGenerator(

cert).setProvider(“BC”));

CMSEnvelopedData ed=edGen.generate(msg,newJceCMSContentEncryptorBuilder(PKCSObjectIdentifiers.rc4)

.setProvider(“BC”).build());

String rslt= newString(Base64.encode(ed.getEncoded()));

System.out.println(rslt);returnrslt;

}/*** 解密数据

*@paramencode 加密后的密文

*@paramcertPath 证书路径

*@paramcertPwd 证书密码

*@paramcharSet 字符编码

*@return*@throwsException*/

public String openEnvelope(String encode, String certPath, String certPwd, String charSet) throwsException {//获取密文

CMSEnvelopedData ed = newCMSEnvelopedData(Base64.decode(encode.getBytes()));

RecipientInformationStore recipients=ed.getRecipientInfos();

Collection c=recipients.getRecipients();

Iterator it=c.iterator();//加载证书

KeyStore ks =KeyStore.getInstance(ksType);

ks.load(newFileInputStream(certPath), certPwd.toCharArray());

String priKeyName= null;if(ks.aliases().hasMoreElements()) {

priKeyName=ks.aliases().nextElement();

}//获取私钥

PrivateKey prikey =(PrivateKey) ks.getKey(priKeyName, certPwd.toCharArray());byte[] recData = null;//解密

if(it.hasNext()) {

RecipientInformation recipient=(RecipientInformation) it.next();

recData= recipient.getContent(newJceKeyTransEnvelopedRecipient(

prikey).setProvider(“BC”));

}return newString(recData, charSet);

}publicMessageUtil() {

Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/234795.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • resnet是卷积神经网络吗_神经网络架构搜索的应用

    resnet是卷积神经网络吗_神经网络架构搜索的应用卷积神经网络在图像识别方面应用广泛,在实际应用在中,识别的准确率不仅仅与数据量有关,还与模型的架构有很大的关联。从首个成功应用于数字识别的卷积神经网络LeNet,到卷积神经网络崛起点AlexNet,以及陆陆续续的ZFNet,VGGNet,Inception系列和ResNet,这些架构在网络深度,宽度,卷积核大小和可视化部分都做了很大的改进,使得卷积神经网络的性能越来越强。

  • SDRAM控制器

    SDRAM控制器

  • spring cloud oauth2 替换用户信息

    spring cloud oauth2 替换用户信息

  • spring data jpa 深入浅出的理解「建议收藏」

    spring data jpa 深入浅出的理解「建议收藏」文章来源于:https://www.cnblogs.com/cmfwm/p/8109433.html这是一篇写得很不错的关于spring-data-jpa的文章,转载到此,方便大家学习交流.本篇进行Spring-data-jpa的介绍,几乎涵盖该框架的所有方面,在日常的开发当中,基本上能满足所有需求。这里不讲解JPA和Spring-data-jpa单独使用,所有的内容都是在和Spri…

  • SLAM技术概述_SRAM工艺

    SLAM技术概述_SRAM工艺导语随着最近几年机器人、无人机、无人驾驶、VR/AR的火爆,SLAM技术也为大家熟知,被认为是这些领域的关键技术之一。本文对SLAM技术及其发展进行简要介绍,分析视觉SLAM系统的关键问题以及在实际应用中的难点,并对SLAM的未来进行展望。1.SLAM技术SLAM(SimultaneousLocalizationandMapping),同步定位与地图构建,最早在机器人领域提出,…

  • 安全帽识别

    U2FsdGVkX1/Grm0Ta4WgSg8mvhSBuX3zjWYamkIvftw=

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号