java pfx加密_.pfx证书 .cer证书MD5withRSA加密

本文介绍如何使用Java处理PFX私钥文件和CER公钥文件进行加密和签名验证。提供了一段使用PKCS12加载PFX私钥并执行MD5withRSA签名的代码,以及读取CER公钥进行签名验证的方法。
摘要由CSDN通过智能技术生成

前言:最近接了一个支付平台,提供了.pfx私钥文件以及.cer公钥文件,对于不常用的加密技术的人来说一头雾水。

代码:

public static String sign(String pfxFile, String pfxPwd, String str, String signature, String coding) {

try {

//获取pfx文件的prikey

Security.addProvider(new BouncyCastleProvider());

KeyStore e = KeyStore.getInstance("PKCS12", "BC");

FileInputStream fis = new FileInputStream(pfxFile);

e.load(fis, pfxPwd.toCharArray());

Enumeration aliases = e.aliases();

String keyAlias = null;

PrivateKey priKey = null;

if (aliases != null) {

while (aliases.hasMoreElements()) {

keyAlias = (String) aliases.nextElement();

priKey = (PrivateKey) e.getKey(keyAlias, pfxPwd.toCharArray());

if (priKey != null) {

break;

}

}

}

//使用Signature加密

Signature signet = Signature.getInstance(signature);

signet.initSign(priKey);

signet.update(str.getBytes(coding));

byte[] signed = signet.sign();

String strSign = new String(Base64.encode(signed));

return strSign;

} catch (Exception ex) {

System.out.println(ex);

}

return null;

}

调用:

System.out.println(sign("C://xxx.pfx","123456","123","MD5withRSA","UTF-8"));

cer公钥代码:

//通过cer文件获取到publickey

String e ="c://xxx.cer";

logger.debug("公钥证书路径:" + e);

FileInputStream in = new FileInputStream(e);

CertificateFactory cf = CertificateFactory.getInstance("X.509");

Certificate cac = cf.generateCertificate(in);

PublicKey pubKey = cac.getPublicKey();

in.close();

//通过pubkey加密

Signature signetcheck = Signature.getInstance("MD5withRSA");

signetcheck.initVerify(pubKey);

signetcheck.update(Base64.decode(msg));

//验证是否一样

if (!signetcheck.verify(Base64.decode(check))) {

throw new  异常("Verify Signature Error");

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值