博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java RSA验签
阅读量:5121 次
发布时间:2019-06-13

本文共 9477 字,大约阅读时间需要 31 分钟。

这几天在跟一个php的小哥哥联调接口,遇到了一些问题记录下来,

直接上代码吧,亲测有效

 

  

 

 

import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.util.Base64Utils;import javax.crypto.Cipher;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.security.KeyFactory;import java.security.Signature;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;public class Rsa {    private static Logger logger = LoggerFactory.getLogger(Rsa.class);    public  String priKey ;    public  String pubKey ;    public static void main(String[] args) {        Rsa rsa = new Rsa();/*        String str = "我要加密这段文字。";        System.out.println("原文:"+"我要加密这段文字。");        String crypt = rsa.encryptByPrivateKey(str);        System.out.println("私钥加密密文:"+crypt);        String result = rsa.decryptByPublicKey(crypt);        System.out.println("原文:"+result);        System.out.println("---");        str = "我要加密这段文字。";        System.out.println("原文:"+"我要加密这段文字。");        crypt = rsa.encryptByPublicKey(str);        System.out.println("公钥加密密文:"+crypt);        result = rsa.decryptByPrivateKey(crypt);        System.out.println("原文:"+result);     Rsa ras = new Rsa();        System.out.println("---");*/        String str = "我要加密这段文字。";        str = "eyJjYXJJbWFnZXMiOiJbe1wiaW1hZ2VUeXBlXCI6MCxcImltYWdlVXJsXCI6XCJodHRwOi8vMTkyLjE2OC4xMDUuMTA1L2luem9uZV9waWNzL2luem9uZS1pbWFnZXMvMjAxOTA3MjQvMTU2Mzk1NDA4Njk1OF83N19wbGF0ZS5qcGdcIn0se1wiaW1hZ2VUeXBlXCI6MSxcImltYWdlVXJsXCI6XCJodHRwOi8vMTkyLjE2OC4xMDUuMTA1L2luem9uZV9waWNzL2luem9uZS1pbWFnZXMvMjAxOTA3MjQvMTU2Mzk1NDA4Njk1OF83N19mdWxsLmpwZ1wifV0iLCJjYXJOdW1iZXIiOiJBRjAyMzYiLCJlbnRyeVRpbWUiOiIxNTYzOTU0MDg2IiwiaGFzTGljZW5zZSI6IjEiLCJwYXJrTnVtYmVyIjoiMDcxOTEzNTc1NTM1NCIsInRpbWVzdGFtcCI6IjE1NjM5NTQwODgifQ==";        Rsa ras = new Rsa();        System.out.println("原文:"+str);        String sign = ras.signByPrivateKey(str);        String signStr = "RjI0akRpV1VWRE9oK2NPV0JkSDFGLzE3SGczeGFUa1Nud1JJa3ExUHZweE9Eb1N0dkhWWDQrK29oRDd3cFFsa1ZZTEFPNmdUaCttZlVreE5mT0lyRHkxWmJsZkg4K1g2RkovL2lsK2ZGTFJ0T25qLyt0cmpZL1VEdHR6aWVoSTJaUHR3MzRIS1hCUmpwTWIyUkFWYW9Ta2RQU2hwakpJamdER1FqWmpoTVhFPQ==";        System.out.println("sign:"+sign);        String result = ras.base64encode(sign.getBytes());        byte[]  result22 = ras.base64decode(signStr);        System.out.println("验签Base64解码:"+new String (result22));        if(rsa.verifyByPublicKey(new String (result22), str)){            System.out.println("验签成功");        } else {            System.out.println("验签失败");        }    }    public Rsa(){        pubKey ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCP5XdjF/eOSVcN7czmL+YCJARYR/65sA6h3e1NLpBQQqgV6eTQtqicMZBvY76ZJZWXnAKxjXJZnKzG29EHmQOL/FdkLI3IktKtkf3DxRhbSs0TqQgx0upECwlL8SGRvHWeApo8wok6IpqYyRY+3IqJjj0ZpKgv7lvPHNdETpCE5wIDAQAB";        priKey ="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAI/ld2MX945JVw3tzOYv5gIkBFhH/rmwDqHd7U0ukFBCqBXp5NC2qJwxkG9jvpkllZecArGNclmcrMbb0QeZA4v8V2QsjciS0q2R/cPFGFtKzROpCDHS6kQLCUvxIZG8dZ4CmjzCiToimpjJFj7ciomOPRmkqC/uW88c10ROkITnAgMBAAECgYAKhPToWp0vWq8xhnvfLAs9htKGfaTigDthm+64ILpOE8Fj8LhYhbHn0TvE2N7bJUM9VRthTXzZjjmXRASQ8J+wpDzLUoGXi6Nixho5YB/F8ZF8ylisJSIigwlZBlLT/unGVRyliGjH7o8sQaccB9DpEXoX0O+vXuG2KtcaO3WaAQJBAPRP5Q8c8ImHnzMoNSI4sm+8dDF2nYwJr1NQ9xRvtrZQUYrvpIdsO73xtxz8nWTvY+S120ddWW3jPGfnkK/KFecCQQCWx8YcsoLMKz29aWHXH6tZTii/JRU46oncixHtbWPhjlX8E2WSrI0mPmX7pKDUegZGquvqOSKPlpmfp8a4KjkBAkEAtfXHaXEpaZUcKjLZGArYQ0Y92BU7E/Cmp0wXKh5mG/VINk1z4fTnrfmYYzt2UpXFdbNIhSduktx6wfyDE5pUowJAVfTDUv7NI/mOs9lMxqeuNjYhcn6Ab7b9KrY5XSIca6yKBi9Em2409VVjLCb47Mg3pbew0BEMS9Et+N9boQepAQJATkyzueYWWsh0weEpKS2er37YYsK16CR9lXHVyaMHRViej4yoHSrhYSWRpa8OQ5ddFYXf4eVFwY28JUHdUb95vw==";    }    /**     * 使用私钥加密     * @see     */    public String encryptByPrivateKey(String data) {        // 加密        String str = "";        try {            byte[] pribyte = base64decode(priKey.trim());            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte);            KeyFactory fac = KeyFactory.getInstance("RSA");            RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);            Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");            c1.init(Cipher.ENCRYPT_MODE, privateKey);            str = base64encode(c1.doFinal(data.getBytes()));        } catch (Exception e) {            e.printStackTrace();        }        return str;    }    /**     * 使用私钥解密     * @see     */    public String decryptByPrivateKey(String data) {        // 加密        String str = "";        try {            byte[] pribyte = base64decode(priKey.trim());            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte);            KeyFactory fac = KeyFactory.getInstance("RSA");            RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);            Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");            c1.init(Cipher.DECRYPT_MODE, privateKey);            byte[] temp = c1.doFinal(base64decode(data));            str = new String(temp);        } catch (Exception e) {            e.printStackTrace();        }        return str;    }    /**     * 使用公钥加密     * @see     */    public String encryptByPublicKey(String data) {        // 加密        String str = "";        try {            byte[] pubbyte = base64decode(pubKey.trim());            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte);            KeyFactory fac = KeyFactory.getInstance("RSA");            RSAPublicKey rsaPubKey = (RSAPublicKey) fac.generatePublic(keySpec);            Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");            c1.init(Cipher.ENCRYPT_MODE, rsaPubKey);            str = base64encode(c1.doFinal(data.getBytes()));        } catch (Exception e) {            e.printStackTrace();        }        return str;    }    /**     * 使用公钥解密     * @see     */    public String decryptByPublicKey(String data) {        // 加密        String str = "";        try {            byte[] pubbyte = base64decode(pubKey.trim());            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte);            KeyFactory fac = KeyFactory.getInstance("RSA");            RSAPublicKey rsaPubKey = (RSAPublicKey) fac.generatePublic(keySpec);            Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");            c1.init(Cipher.DECRYPT_MODE, rsaPubKey);            byte[] temp = c1.doFinal(base64decode(data));            str = new String(temp);        } catch (Exception e) {            e.printStackTrace();        }        return str;    }    /**     * 本方法使用SHA1withRSA签名算法产生签名     * @param  src 签名的原字符串     * @return String 签名的返回结果(16进制编码)。当产生签名出错的时候,返回null。     */    public String signByPrivateKey(String src) {        try {            Signature sigEng = Signature.getInstance("SHA1withRSA");            byte[] pribyte = base64decode(priKey.trim());            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte);            KeyFactory fac = KeyFactory.getInstance("RSA");            RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);            sigEng.initSign(privateKey);            sigEng.update(src.getBytes());            byte[] signature = sigEng.sign();            return base64encode(signature);        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    /**     * 使用共钥验证签名     * @param sign     * @param src     * @return     */    public boolean verifyByPublicKey(String sign, String src) {        try {            Signature sigEng = Signature.getInstance("SHA1withRSA");            byte[] pubbyte = base64decode(pubKey.trim());            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte);            KeyFactory fac = KeyFactory.getInstance("RSA");            RSAPublicKey rsaPubKey = (RSAPublicKey) fac.generatePublic(keySpec);            sigEng.initVerify(rsaPubKey);            sigEng.update(src.getBytes());            byte[] sign1 = base64decode(sign);            return sigEng.verify(sign1);        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     *  base64加密     * @param bstr     * @return     */    @SuppressWarnings("restriction")    public String base64encode(byte[] bstr) {        String str = Base64Utils.encodeToString(bstr);        str = str.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");        return str;    }    /**     * base64解密     * @param str     * @return byte[]     */    @SuppressWarnings("restriction")    public byte[] base64decode(String str) {        byte[] bt = null;        try {            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();            bt = decoder.decodeBuffer(str);        } catch (IOException e) {            e.printStackTrace();        }        return bt;    }    /**     * 从文件中读取所有字符串     * @param fileName     * @return	String     */    private String readStringFromFile(String fileName){        StringBuffer str = new StringBuffer();        try {            File file = new File(fileName);            FileReader fr = new FileReader(file);            char[] temp = new char[1024];            while (fr.read(temp) != -1) {                str.append(temp);            }            fr.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return str.toString();    }}

  

转载于:https://www.cnblogs.com/wudi521/p/11239692.html

你可能感兴趣的文章
cocos2dx 3.x simpleAudioEngine 长音效被众多短音效打断问题
查看>>
存储(硬件方面的一些基本术语)
查看>>
观察者模式
查看>>
Weka中数据挖掘与机器学习系列之基本概念(三)
查看>>
Win磁盘MBR转换为GUID
查看>>
大家在做.NET B/S项目的时候多用什么设技术啊?
查看>>
Java SE和Java EE应用的性能调优
查看>>
Android设计模式系列--原型模式
查看>>
免费的论文查重网站
查看>>
C语言程序第一次作业
查看>>
leetcode-Sort List
查看>>
中文词频统计
查看>>
了解node.js
查看>>
想做移动开发,先看看别人怎么做
查看>>
Eclipse相关集锦
查看>>
虚拟化架构中小型机构通用虚拟化架构
查看>>
继承条款effecitve c++ 条款41-45
查看>>
Java泛型的基本使用
查看>>
1076 Wifi密码 (15 分)
查看>>
noip模拟赛 党
查看>>