首页 > 其他分享 >RSA加解密懒得写了,记录一下代码

RSA加解密懒得写了,记录一下代码

时间:2024-05-15 09:57:05浏览次数:8  
标签:Exception 懒得 return String 加解密 RSA offSet throws out

package com.hoyo.common.core.utils;

import com.hoyo.common.core.utils.uuid.UUID;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtil {
/**
* 加密算法RSA
*/
private static final String KEY_ALGORITHM = "RSA";

/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;

/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 256;


/**
* Method: decryptBASE64
* description: 解码返回byte
*
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}

/**
* Method: encryptBASE64
* description: 编码返回字符串
*
* @param key
* @return
* @throws Exception
*/
public static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}

/**
* 获取base64加密后的字符串的原始公钥
*
* @param keyStr
* @return
* @throws Exception
*/
public static Key getPublicKeyFromBase64KeyEncodeStr(String keyStr) throws Exception {
byte[] keyBytes = decryptBASE64(keyStr);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
Key publicKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(x509KeySpec);
return publicKey;
}

/**
* 获取base64加密后的字符串的原始私钥
*
* @param keyStr
* @return
* @throws Exception
*/
public static Key getPrivateKeyFromBase64KeyEncodeStr(String keyStr) throws Exception {
byte[] keyBytes = decryptBASE64(keyStr);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
Key privateKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(pkcs8KeySpec);
return privateKey;
}

/**
* Method: encrypt
* description: 公钥分段加密
*
* @param dataStr 加密内容,明文
* @param publicKeyStr 公钥内容
* @return 密文
* @throws Exception
*/
public static String encrypt(String dataStr, String publicKeyStr) throws Exception {
ByteArrayOutputStream out = null;
String encodedDataStr = null;
try {
out = new ByteArrayOutputStream();
byte[] data = dataStr.getBytes("utf-8");
// 获取原始公钥
Key decodePublicKey = getPublicKeyFromBase64KeyEncodeStr(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, decodePublicKey);
int inputLen = data.length;
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();
encodedDataStr = new String(encryptBASE64(encryptedData));
} catch (Exception e) {
throw e;
} finally {
try {
out.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
return encodedDataStr;
}

/**
* Method: encrypt
* description: 私钥分段解密
*
* @return 明文
* @throws Exception
*/
public static String decrypt(String dataStr, String privateKey) throws Exception {
ByteArrayOutputStream out = null;
String decodedDataStr = null;
try {
out = new ByteArrayOutputStream();

byte[] encryptedData = decryptBASE64(dataStr);
// 获取原始私钥
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key decodePrivateKey = getPrivateKeyFromBase64KeyEncodeStr(privateKey);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, decodePrivateKey);
int inputLen = encryptedData.length;

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();
decodedDataStr = new String(decryptedData, "utf-8");
} catch (Exception e) {
throw e;
} finally {
try {
out.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
return decodedDataStr;
}

public static void main(String[] args) {
// 公钥
String publicKey = "";

// 私钥
String privateKey = "";

/**
* 加密及获取签名
*/
// 源报文(未加密)
try {
for (int i = 0; i < 10; i++) {
String msg = "USERID=" + UUID.fastUUID() + "&MOBILE=1888888888";
String enc_msg = RSAUtil.encrypt(msg, publicKey);
BASE64Encoder encoder = new BASE64Encoder();
enc_msg = encoder.encode(enc_msg.getBytes("UTF-8"));
enc_msg = enc_msg.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");

System.out.println("------------------------");
System.out.println(enc_msg);
}
// 公钥加密得到密文并使用base64处理

// 根据源报文+私钥获得MD5签名
// String mac_info = SignMD5Utils.getMD5(msg + privateKey);

/**
* 解密及验签
*/
// base64逆处理并用私钥解密
BASE64Decoder decoder = new BASE64Decoder();
String decoStr = new String(decoder.decodeBuffer(""), StandardCharsets.UTF_8);
String dec_msg = RSAUtil.decrypt(decoStr, privateKey);
System.out.println("------------解密密------------");
System.out.println(dec_msg);



} catch (Exception e) {
e.printStackTrace();
}
}
}

标签:Exception,懒得,return,String,加解密,RSA,offSet,throws,out
From: https://www.cnblogs.com/michaelcnblogs/p/18193207

相关文章

  • RSA 具有单向陷门置换的性质
    这篇文章我们介绍RSA的单向性,置换型等等.我们给出formal的RSA假设:RSA假设.给定一个三元组\((N,e,y)\),其中\(N\)是大素数\(p,q\)的乘积,\(gcd(e,\Phi(N))=1\),\(y\in\mathbbZ_n^*\),那么对于任意的PPT敌手\(\mathcalA\),能够找到\(x\)使得\(x^e=y......
  • CTF中RSA相关题型总结(持续更新)
    e很小时:importgmpy2fromfunctoolsimportreducefromCrypto.Util.numberimportlong_to_bytesdefCRT(items):N=reduce(lambdax,y:x*y,(i[1]foriinitems))result=0fora,ninitems:m=N//nd,r,s=gmpy2.gcdext(......
  • P10224 [COCI 2023/2024 #3] Vrsar 题解
    P10224[COCI2023/2024#3]Vrsar题解知识点前缀和思想,贪心。题意分析我觉得题目挺清晰了……思路部分分没必要,OK?我不会告诉你我考场上打部分分打了30min,还只有8分。正解我们设一个方案\(S\)为\(\{x_1,x_2...x_n\}\),其中\(x_i\)表示第\(i\)个滑雪场的......
  • RequestBodyAdvice用法详解-参数加解密示例
     在实际项目中,我们常常需要在请求前后进行一些操作,比如:参数解密/返回结果加密,打印请求参数和返回结果的日志等。这些与业务无关的东西,我们不希望写在controller方法中,造成代码重复可读性变差。这里,我们讲讲使用@ControllerAdvice和RequestBodyAdvice、ResponseBodyAdvice来对请......
  • 基于nodeje的RSA加解密
    RAS是一种非对称加密,可以用公钥加密,私钥解密也可以反过来用私钥加密,公钥解密;以下是其实现方式,与java后台匹配,实现双向加解密。/***RSA最大加密明文大小*/constMAX_ENCRYPT_BLOCK=245;/***RSA最大解密密文大小*/constMAX_DECRYPT_BLOCK=256;通过fs.readFil......
  • Server-side vulnerabilities :path traversal
    来自bp的学院,提供了靶机,是个学习好地方服务器漏洞之路径遍历 就是说网站提供的图片,如果直接通过src="/loadImage?filename=xxx.jpg“读取的话,可以通过构造”filename=../../../etc/passwd"参数,拿到服务器的passwd文件,这样能读取服务器的用户放一个靶机地址:https://portswigg......
  • Rsa1
    一、1、两个大素数:p,q(验证13是否是素数则输入13,显示结果为13=13,可见13是素数)2、模数n:n=p*q(分解出素数p和q的网站http://www.factordb.com/)3、计算欧拉函数φ(n)=(p-1)*(q-1)4、公钥指数:e与f(n)互质,且与1<e<f(n)amodb=1一般为655375、私钥指数d满足e*d=1(mod(f(n))......
  • Luminar Neo 1.19.0 (macOS Universal) - 创新 AI 图像编辑器
    LuminarNeo1.19.0(macOSUniversal)-创新AI图像编辑器利用尖端的人工智能生成技术,轻松增强照片效果请访问原文链接:LuminarNeo1.19.0(macOSUniversal)-创新AI图像编辑器,查看最新版。原创作品,转载请保留出处。作者主页:sysin.org提升您的照片编辑能力。你想象......
  • 非对称加密中,加解密和签名
    在非对称加密中,加解密使用的密钥取决于具体的用途:加密:通常情况下,当想要确保数据的机密性,即希望只有特定接收方能够读取信息时,发送方会使用接收方的公钥对数据进行加密。这样一来,只有拥有对应私钥的接收方才能够解密并查看原始信息。解密:对应地,接收方收到加密后的数据后,......
  • Pixelmator Pro 3.5.10 Flare (macOS Universal) - 专业图像编辑工具
    PixelmatorPro3.5.10Flare(macOSUniversal)-专业图像编辑工具Photoshop的卓越替代软件请访问原文链接:PixelmatorPro3.5.10Flare(macOSUniversal)-专业图像编辑工具,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgPixelmatorPro真正基于AppleMac......