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