用RSA技术加密解密
Posted yxj808
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用RSA技术加密解密相关的知识,希望对你有一定的参考价值。
package com.sundear.demo;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
/**
* RSA加解密
* @author jiafuwei
* created at 2017/6/8
*/
@SpringBootTest(classes = DemoApplication.class)
@RunWith(SpringRunner.class)
class DemoApplicationTests {
private static KeyFactory keyFactory = null;
@Value("${RSA.MAX_DECRYPT_BLOCK}")
int MAX_DECRYPT_BLOCK;
@Value("${RSA.MAX_ENCRYPT_BLOCK}")
int MAX_ENCRYPT_BLOCK;
@Value("${RSA.priKeyText}")
String PrivateKey;
@Value("${RSA.pubKeyText}")
String PublicKey;
/**
* 使用公钥进行分段加密
* @param dataStr 要加密的数据
* @return 公钥base64字符串
* @throws Exception
*/
public String encryptByPublicKey(String dataStr)
throws Exception {
//要加密的数据
System.out.println("要加密的数据:"+dataStr);
byte[] data = dataStr.getBytes();
// 对公钥解密
byte[] keyBytes = Base64.decode(PublicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
Key decodePublicKey = null;
try {
keyFactory = KeyFactory.getInstance("RSA");
decodePublicKey = keyFactory.generatePublic(x509KeySpec);
} catch (Exception e) {
e.printStackTrace();
}
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, decodePublicKey);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
String encodedDataStr = new String(Base64.encode(encryptedData));
System.out.println("公钥加密后的数据:"+encodedDataStr);
return encodedDataStr;
}
/**
* 使用私钥进行分段解密
* @param dataStr 使用base64处理过的密文
* @return 解密后的数据
* @throws Exception
*/
public String decryptByPrivateKey(String dataStr)
throws Exception {
byte[] encryptedData = Base64.decode(dataStr);
System.out.println(dataStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] keyBytes = Base64.decode(PrivateKey);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
Key decodePrivateKey=null;
try {
decodePrivateKey = keyFactory.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, decodePrivateKey);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
String decodedDataStr = new String(decryptedData,"utf-8");
System.out.println("私钥解密后的数据:"+decodedDataStr);
return decodedDataStr;
}
@Test
public void test2()throws Exception{
String objectStr="{"Phone":"17717636102","RegisterSubChannel":""," +
""Gender":"1","OpenId":"u66f9u9896u6645","StoreCode":"11220000"," +
""EmployeeCode":""}";
String s= this.encryptByPublicKey(objectStr);
this.decryptByPrivateKey(s);