前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >.pfx证书 .cer证书MD5withRSA加密

.pfx证书 .cer证书MD5withRSA加密

作者头像
王念博客
发布2019-07-25 17:47:30
1.4K0
发布2019-07-25 17:47:30
举报
文章被收录于专栏:王念博客王念博客王念博客

前言:最近接了一个支付平台,提供了.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");
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档