这几天在跟一个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();
} }

  

java RSA验签的更多相关文章

  1. java RSA 加签验签【转】

    引用自: http://blog.csdn.net/wangqiuyun/article/details/42143957/ java RSA 加签验签 package com.testdemo.co ...

  2. ios RSA 验签加密解密

    关于公钥和私钥的生成,网上有很多本地生产的方法,我遇到的问题是,按照网上生产的方式生成7个文件,本地使用没有问题,但是和后台交互就不行了. 发现生成公钥和私钥的没有那么麻烦,使用在线生产工具就能使用, ...

  3. JAVA/PHP/C#版RSA验签--转

    本文是上一篇文章的兄弟篇,上篇文章介绍了客户端的sdk中如何基于JAVA/PHP/C#使用RSA私钥签名,然后服务端基于JAVA使用RSA公钥验签,客户端签名/服务端验签的模式只能帮助服务端检查客户端 ...

  4. 【加密】RSA验签及加密

    通过OpenSSL生成公私钥文件(如果没有OpenSSL工具建议下载Cmder工具自带OpenSSL指令) 1.生成RSA密钥的方法 genrsa -out private-rsa.key 2048 ...

  5. Java 签名验签工具类

    public class SignatureUtil { private static final String CHARSET = "UTF-8"; private static ...

  6. php--php调java接口验签

    <?php namespace Fmall_cloud\Model; use Think\Model; class DealJavaModel extends Model { /** * @ti ...

  7. java/php/c#版rsa签名以及java验签实现--转

    在开放平台领域,需要给isv提供sdk,签名是Sdk中需要提供的功能之一.由于isv使用的开发语言不是单一的,因此sdk需要提供多种语言的版本.譬如java.php.c#.另外,在电子商务尤其是支付领 ...

  8. java/php/c#版rsa签名以及验签实现

    本文为转载,请转载请注明地址: 原文地址为        http://xw-z1985.iteye.com/blog/1837376 在开放平台领域,需要给isv提供sdk,签名是Sdk中需要提供的 ...

  9. .NET Core RSA 签名和验签(密钥为 16 进制编码)

    使用 OpenSSL 生成公私钥对,命令: $ openssl genrsa -out rsa_1024_priv.pem $ openssl pkcs8 -topk8 -inform PEM -in ...

随机推荐

  1. Spring注解基础学习总结

    1.依赖注入注解: @Component:Bean注入到Spring容器组件(通用) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE):Bean作用域( ...

  2. c#WinForm程序调用vsto动态库,已解决

    最近做一个vsto的项目,涉及到Form程序调用vsto动态库,弄了半天,搜了很多资料终于搞定了,把积累写下来备以后用.相关网址: https://stackoverflow.com/question ...

  3. SpringBoot防止重复请求,重复表单提交超级简单的注解实现

    1. 注解接口 /** * @description 防止表单重复提交注解 */@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHO ...

  4. 表单 用jquery做输入脱离焦点 进行正则验证

    <!-- 账号登录块 -->       <form class="form1" action="" method="get&quo ...

  5. JVM中堆栈

    1.JVM是基于堆栈的虚拟机.JVM为每个新创建的线程都分配一个堆栈.也就是说,对于一个Java程序来说,它的运行就是通过对堆栈的操作来完成的.堆栈以帧为单位保存线程的状态.JVM对堆栈只进行两种操作 ...

  6. Javascript加载talbe(包含分页、数据下载功能)

    效果图如下: 首先简单说明一下,后面会给所涉及到的代码都贴上来的. 1.excel图标是一个用户控件,用来触发下载 2.首页.上页......每页多少条,这一块是一个整体,你可以选择放置在表格下面,或 ...

  7. C/C++实现单向循环链表(尾指针,带头尾节点)

    C语言实现单向循环链表,主要功能为空链表创建,链表初始化(头插法,尾插法),链表元素读取,按位置插入,(有序链表)按值插入,按位置删除,按值删除,清空链表,销毁链表. 单向循环链表和单向链表的区别:( ...

  8. (20)Oracle函数

    substr 截取字段 substr(字符串,截取开始位置,截取长度) substr(str,n,m) 第二,三参数可以省略, 第二个参数为负数时表示从倒数第n位开始向后截取m个 round(str, ...

  9. windows sdk版本 之 并查集生成迷宫

    #include <cstdlib> #include <ctime> #include<algorithm> using namespace std; exter ...

  10. namespace 命名空间

    namespace作用:资源隔离 当我们不指定namespace时,默认放在default下 创建namespace kubectl create namespace 资源名称 在生产中,我们建议一个 ...