|

楼主 |
发表于 2022-6-2 20:54:00
|
显示全部楼层
本帖最后由 徐柳婧 于 2022-6-2 23:35 编辑
RSAEncrypt.java
- package com.ihep;
- import javax.crypto.BadPaddingException;
- import javax.crypto.Cipher;
- import javax.crypto.IllegalBlockSizeException;
- import javax.crypto.NoSuchPaddingException;
- import java.io.*;
- import java.security.*;
- import java.security.interfaces.RSAPrivateKey;
- import java.security.interfaces.RSAPublicKey;
- import java.security.spec.InvalidKeySpecException;
- import java.security.spec.PKCS8EncodedKeySpec;
- import java.security.spec.X509EncodedKeySpec;
- private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6',
- '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
- public static void genKeyPair(String filePath) {
- // 密钥对生成器
- KeyPairGenerator keyPairGen = null;
- try {
- // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
- keyPairGen = KeyPairGenerator.getInstance("RSA");
- } catch (NoSuchAlgorithmException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // 初始化密钥对生成器,密钥大小为96-1024位
- keyPairGen.initialize(1024, new SecureRandom());
- // 生成一个密钥对,保存在keyPair中
- KeyPair keyPair = keyPairGen.generateKeyPair();
- // 得到私钥
- RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
- // 得到公钥
- RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
- try {
- // 得到公钥字符串
- String publicKeyString = Base64.encode(publicKey.getEncoded());
- // 得到私钥字符串
- String privateKeyString = Base64.encode(privateKey.getEncoded());
- // 将密钥对写入到文件
- FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
- FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
- BufferedWriter pubbw = new BufferedWriter(pubfw);
- BufferedWriter pribw = new BufferedWriter(prifw);
- pubbw.write(publicKeyString);
- pribw.write(privateKeyString);
- pubbw.flush();
- pubbw.close();
- pubfw.close();
- pribw.flush();
- pribw.close();
- prifw.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static String loadPublicKeyByFile(String path) throws Exception {
- try {
- BufferedReader br = new BufferedReader(new FileReader(path
- + "/publicKey.keystore"));
- String readLine = null;
- StringBuilder sb = new StringBuilder();
- while ((readLine = br.readLine()) != null) {
- sb.append(readLine);
- }
- br.close();
- return sb.toString();
- } catch (IOException e) {
- throw new Exception("公钥数据流读取错误");
- } catch (NullPointerException e) {
- throw new Exception("公钥输入流为空");
- }
- }
- public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
- throws Exception {
- try {
- byte[] buffer = Base64.decode(publicKeyStr);
- KeyFactory keyFactory = KeyFactory.getInstance("RSA");
- X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
- return (RSAPublicKey) keyFactory.generatePublic(keySpec);
- } catch (NoSuchAlgorithmException e) {
- throw new Exception("无此算法");
- } catch (InvalidKeySpecException e) {
- throw new Exception("公钥非法");
- } catch (NullPointerException e) {
- throw new Exception("公钥数据为空");
- }
- }
- public static String loadPrivateKeyByFile(String path) throws Exception {
- try {
- BufferedReader br = new BufferedReader(new FileReader(path
- + "/privateKey.keystore"));
- String readLine = null;
- StringBuilder sb = new StringBuilder();
- while ((readLine = br.readLine()) != null) {
- sb.append(readLine);
- }
- br.close();
- /** 该字符串从私钥文件中获取,称之为私钥字符串
- * MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALaIDyyav7J8oD/8sONfP772aa1foDlHmoXRArqe+2po14c1q7nGR8DLk
- * 55J0sgxt/EOvtvxtwo4cPFtoLSBzdKVn/ZmR7uyHQXsMzqcmz7n7DGAzNNqxlu0SLHVjZ4HscWxnC+dGa037Ec9m5DKRT6aMckNmxZp3G
- * xic9wzId6zAgMBAAECgYEAhpOUFH/XvEH0aJjm1gzA1AubaI8rc2/edrDeQTe8B/1agr7IaMTO3E97++VT+fPmOV10zHbPTELGysnYBZ3
- * 6X/wLaKs+GMO/uewNAsyu46u3izwNVCygBiM62mlmhk3Y9J8ZcmoQHzXGV0p0TuGJsIlAofCAN1ielWLPcEVUPckCQQDoQm4GKe2C26oU
- * aXRwLy2WLczfmqLTlJ8QyJs8ruL78JikhDgLWaLPBJ+lHmTxahC4HjJ9LhNxNVcpbyMiHhM1AkEAyTBjkOGwBJTlYMmS1hn6BoqA5xCRF
- * Iv8gZZMxj+xcvSSEfZU9ObVArOBQRUoIO3GdsyaVfG/DNwuP7zGI16/RwJBAMfyIEu4HpsvxeyKmE3Xn5QQ27WHpzMkWAeX22RTXl7r0k
- * yW8rR6txkm7tS0JMxbtgb7IBX564zjEaU+4u0FHR0CQG+v+zYM9Ag3GHd4r5lH5nMHJLQhkEjVxaGy7IAKD9p/Ry/NjjA+jPXo7NJSimp
- * tVYXR48PeZm8fNFWR2HT+PjUCQFu3yN71iiXA0EW35Y1HHIE814gUV/O5T4gpUNzK9NLvHLFQNbzgoZER5yIGgBWDju1keBkojm8P69A7
- * qdtXILU=
- */
- return sb.toString();
- } catch (IOException e) {
- throw new Exception("私钥数据读取错误");
- } catch (NullPointerException e) {
- throw new Exception("私钥输入流为空");
- }
- }
- public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
- throws Exception {
- try {
- byte[] buffer = Base64.decode(privateKeyStr);
- PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
- KeyFactory keyFactory = KeyFactory.getInstance("RSA");
- return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
- } catch (NoSuchAlgorithmException e) {
- throw new Exception("无此算法");
- } catch (InvalidKeySpecException e) {
- throw new Exception("私钥非法");
- } catch (NullPointerException e) {
- throw new Exception("私钥数据为空");
- }
- }
- public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
- throws Exception {
- if (publicKey == null) {
- throw new Exception("加密公钥为空, 请设置");
- }
- Cipher cipher = null;
- try {
- // 使用默认RSA
- cipher = Cipher.getInstance("RSA");
- // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
- // 初始化算法:公钥加密
- cipher.init(Cipher.ENCRYPT_MODE, publicKey);
- // 公钥加密后的字节数组
- byte[] output = cipher.doFinal(plainTextData);
- return output;
- } catch (NoSuchAlgorithmException e) {
- throw new Exception("无此加密算法");
- } catch (NoSuchPaddingException e) {
- e.printStackTrace();
- return null;
- } catch (InvalidKeyException e) {
- throw new Exception("加密公钥非法,请检查");
- } catch (IllegalBlockSizeException e) {
- throw new Exception("明文长度非法");
- } catch (BadPaddingException e) {
- throw new Exception("明文数据已损坏");
- }
- }
- public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
- throws Exception {
- if (privateKey == null) {
- throw new Exception("加密私钥为空, 请设置");
- }
- Cipher cipher = null;
- try {
- // 使用默认RSA
- cipher = Cipher.getInstance("RSA");
- // 初始化算法:私钥加密
- cipher.init(Cipher.ENCRYPT_MODE, privateKey);
- // 加密后的密文数据,以字符数组的形式存在
- byte[] output = cipher.doFinal(plainTextData);
- return output;
- } catch (NoSuchAlgorithmException e) {
- throw new Exception("无此加密算法");
- } catch (NoSuchPaddingException e) {
- e.printStackTrace();
- return null;
- } catch (InvalidKeyException e) {
- throw new Exception("加密私钥非法,请检查");
- } catch (IllegalBlockSizeException e) {
- throw new Exception("明文长度非法");
- } catch (BadPaddingException e) {
- throw new Exception("明文数据已损坏");
- }
- }
- public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
- throws Exception {
- if (privateKey == null) {
- throw new Exception("解密私钥为空, 请设置");
- }
- Cipher cipher = null;
- try {
- // 使用默认RSA
- cipher = Cipher.getInstance("RSA");
- // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
- // 初始化解密算法:私钥解密
- cipher.init(Cipher.DECRYPT_MODE, privateKey);
- // 解密,生成以字符数组形式存在的明文数据
- byte[] output = cipher.doFinal(cipherData);
- return output;
- } catch (NoSuchAlgorithmException e) {
- throw new Exception("无此解密算法");
- } catch (NoSuchPaddingException e) {
- e.printStackTrace();
- return null;
- } catch (InvalidKeyException e) {
- throw new Exception("解密私钥非法,请检查");
- } catch (IllegalBlockSizeException e) {
- throw new Exception("密文长度非法");
- } catch (BadPaddingException e) {
- throw new Exception("密文数据已损坏");
- }
- }
- public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
- throws Exception {
- if (publicKey == null) {
- throw new Exception("解密公钥为空, 请设置");
- }
- Cipher cipher = null;
- try {
- // 使用默认RSA
- cipher = Cipher.getInstance("RSA");
- // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
- // 初始化加密算法:公钥解密
- cipher.init(Cipher.DECRYPT_MODE, publicKey);
- byte[] output = cipher.doFinal(cipherData);
- // 以字符数组形式存在的明文数据
- return output;
- } catch (NoSuchAlgorithmException e) {
- throw new Exception("无此解密算法");
- } catch (NoSuchPaddingException e) {
- e.printStackTrace();
- return null;
- } catch (InvalidKeyException e) {
- throw new Exception("解密公钥非法,请检查");
- } catch (IllegalBlockSizeException e) {
- throw new Exception("密文长度非法");
- } catch (BadPaddingException e) {
- throw new Exception("密文数据已损坏");
- }
- }
- public static String byteArrayToString(byte[] data) {
- StringBuilder stringBuilder = new StringBuilder();
- for (int i = 0; i < data.length; i++) {
- // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
- stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
- // 取出字节的低四位 作为索引得到相应的十六进制标识符
- stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
- if (i < data.length - 1) {
- stringBuilder.append(' ');
- }
- }
- return stringBuilder.toString();
- }
- }
复制代码
|
|