码迷,mamicode.com
首页 > 其他好文 > 详细

用RSA技术加密解密

时间:2020-08-03 23:08:20      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:test   lock   sts   ast   nal   ring   catch   not   style   

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);
JSONObject jsonObject=new JSONObject(objectStr);
System.out.println(jsonObject);
System.out.println(jsonObject.getString("Phone"));
jsonObject.put("ClientId","1");



}


}

用RSA技术加密解密

标签:test   lock   sts   ast   nal   ring   catch   not   style   

原文地址:https://www.cnblogs.com/yxj808/p/13428262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!