数字信封(RSA和DES整合测试)加密技术

2024-05-19 02:18

本文主要是介绍数字信封(RSA和DES整合测试)加密技术,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

http://git.oschina.net/xshuai/ai 源码地址

  • DES加解密方法

package com.xs.demo.util;
import java.security.SecureRandom;import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/*** DES对称算法加解密方法类* @author 小帅丶* @类名称  DES* @remark DES 密钥长度必须是8* @date  2017-6-21*/
public class DES {/*** DES算法加密* @param datasource 需要加密的数据* @param password des密钥* @return byte* @author 小帅丶*/public static byte[] encrypt(byte[] datasource,String password) {try {//DES算法要求有一个可信任的随机源SecureRandom random = new SecureRandom();//创建一个DesKeySpec对象DESKeySpec desKeySpec = new  DESKeySpec(password.getBytes());//创建一个密钥工厂SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");//将DesKeySpec对象转换成SecrectKey对象SecretKey secretKey = keyFactory.generateSecret(desKeySpec);// Cipher对象实例化DES算法进行解密操作Cipher cipher = Cipher.getInstance("DES");//用密钥初始化Cipher对象cipher.init(Cipher.ENCRYPT_MODE, secretKey,random);//开始加密返回byte字节数据return cipher.doFinal(datasource);} catch (Exception e) {e.getMessage();}return null;}/*** DES算法解密* @param str 需要解密的数据 * @param password des密钥* @return byte* @author 小帅丶*/public static byte[] decrypt(byte [] str,String password){try {//DES算法要求有一个可信任的随机源SecureRandom random = new SecureRandom();//创建一个DesKeySpec对象DESKeySpec desKeySpec = new  DESKeySpec(password.getBytes());//创建一个密钥工厂SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");//将DesKeySpec对象转换成SecrectKey对象SecretKey secretKey = keyFactory.generateSecret(desKeySpec);// Cipher对象实例化DES算法进行解密操作Cipher cipher = Cipher.getInstance("DES");//用密钥初始化Cipher对象cipher.init(Cipher.DECRYPT_MODE, secretKey,random);//开始解密返回byte字节数据return cipher.doFinal(str);} catch (Exception e) {e.getMessage();}return null;}
}

  • RSA+DES整合测试加解密数据。又名数字信封


package com.xs.demo.util;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;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;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;import com.xiaoleilu.hutool.lang.Base64;/*** * @author 小帅丶* @类名称 RSAEncrypt* @remark RSA测试生成公私钥对* @date 2017-6-14*/
public class RSAEncrypt {public static void main(String[] args) throws Exception {
//		getKeyPair("G:/Envolope"); 生成RSA公私钥对System.out.println("----------RSA与DES整合算法测试(又名数字信封)----------");String path = "G:/Envolope";String text = "测试RSADES";byte [] plainTextData = DES.encrypt(text.getBytes(), "12345678");byte [] data = encrypt(loadPrivateKeyByStr(loadPrivateKeyByFile(path)), plainTextData);System.out.println("原始数据\t"+text);System.out.println("DES加密后的数据\t"+Base64.encode(plainTextData));System.out.println("CA私钥加密后的数据"+Base64.encode(data));System.out.println("开始解密");byte [] data2 = decrypt(loadPublicKeyByStr(loadPublicKeyByFile(path)), data);System.out.println("公钥解密出的数据\t"+Base64.encode(data2));byte [] plainTextData2 = DES.decrypt(data2, "12345678");System.out.println("解密出来的数据\t"+new String(plainTextData2));}/*** 字节数据转字符串专用集合*/private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };/*** 随机生成密钥对* * @param savefilePath*            证书保存目录*/public static void getKeyPair(String savefilePath) {// 基于RSA算法生成 公私钥对KeyPairGenerator keyPairGen = null;try {keyPairGen = KeyPairGenerator.getInstance("RSA");} catch (NoSuchAlgorithmException e) {e.printStackTrace();}// 初始化密钥对生成器 大小为1024位keyPairGen.initialize(1024, new SecureRandom());// 生成密钥对 保存在keyPair中KeyPair keyPair = keyPairGen.generateKeyPair();// 得到私钥RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();// 得到公钥RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();try {// 得到私钥字符串String privateKeyString = Base64.encode(privateKey.getEncoded());// 得到公钥字符串String publicKeyString = Base64.encode(publicKey.getEncoded());// 将密钥对写入到文件FileWriter pubfw = new FileWriter(savefilePath+ "/publicKey.keystore");FileWriter prifw = new FileWriter(savefilePath+ "/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 (IOException e) {e.printStackTrace();}}/*** 从文件中输入流加载公钥* * @param path*            公钥的地址* @return String* @throws Exception*/public static String loadPublicKeyByFile(String path) throws Exception {try {BufferedReader br = new BufferedReader(new FileReader(path+ "/publicKey.keystore"));String readLine = null;StringBuffer sb = new StringBuffer();while ((readLine = br.readLine()) != null) {sb.append(readLine);}br.close();return sb.toString();} catch (FileNotFoundException e) {throw new Exception("公钥文件未找到或不存在");} catch (IOException e) {throw new Exception("公钥输入流为空");}}/*** 从字符串中读取公钥* * @param publicKeyStr* @return RSAPublicKey* @throws Exception*/public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)throws Exception {byte[] buffer = Base64.decode(publicKeyStr);try {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("公钥非法");}}/*** 从文件中输入流加载私钥* * @param path*            私钥的地址* @return String* @throws Exception*/public static String loadPrivateKeyByFile(String path) throws Exception {try {BufferedReader br = new BufferedReader(new FileReader(path+ "/privateKey.keystore"));String readLine = null;StringBuffer sb = new StringBuffer();while ((readLine = br.readLine()) != null) {sb.append(readLine);}br.close();return sb.toString();} catch (FileNotFoundException e) {throw new Exception("私钥文件未找到或不存在");} catch (IOException e) {throw new Exception("私钥输入流为空");}}/*** 从字符串中读取私钥* * @param privateKeyStr* @return RSAPrivateKey* @throws Exception*/public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)throws Exception {byte[] buffer = Base64.decode(privateKeyStr);try {KeyFactory keyFactory = KeyFactory.getInstance("RSA");PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);} catch (NoSuchAlgorithmException e) {throw new Exception("算法不存在");} catch (InvalidKeySpecException e) {throw new Exception("私钥非法");}}/*** 公钥加密过程* * @param publicKey*            公钥* @param plainTextData*            明文数据* @return 明文* @throws Exception*             加密过程中的异常信息*/public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)throws Exception {if (publicKey == null) {throw new Exception("加载公钥为空,请修改");}try {Cipher cipher = null;cipher = Cipher.getInstance("RSA");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("明文数据已损坏");}}/*** 私钥加密过程* * @param privateKey*            私钥* @param plainTextData*            明文数据* @return 明文* @throws Exception*             加密过程中的异常信息*/public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)throws Exception {if (privateKey == null) {throw new Exception("加密私钥为空, 请设置");}Cipher cipher = null;try {// 使用默认RSAcipher = 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("明文数据已损坏");}}/*** 私钥解密过程* * @param privateKey*            私钥* @param cipherData*            密文数据* @return 明文* @throws Exception*             解密过程中的异常信息*/public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)throws Exception {if (privateKey == null) {throw new Exception("解密私钥为空, 请设置");}Cipher cipher = null;try {// 使用默认RSAcipher = Cipher.getInstance("RSA");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("密文数据已损坏");}}/*** 公钥解密过程* * @param publicKey*            公钥* @param cipherData*            密文数据* @return 明文* @throws Exception*             解密过程中的异常信息*/public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)throws Exception {if (publicKey == null) {throw new Exception("解密公钥为空, 请设置");}Cipher cipher = null;try {// 使用默认RSAcipher = 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("密文数据已损坏");}}/*** 字节数据转十六进制字符串* * @param data*            输入数据* @return 十六进制内容*/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();}}


这篇关于数字信封(RSA和DES整合测试)加密技术的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/995754

相关文章

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

Springboot整合Redis主从实践

《Springboot整合Redis主从实践》:本文主要介绍Springboot整合Redis主从的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言原配置现配置测试LettuceConnectionFactory.setShareNativeConnect

使用SpringBoot整合Sharding Sphere实现数据脱敏的示例

《使用SpringBoot整合ShardingSphere实现数据脱敏的示例》ApacheShardingSphere数据脱敏模块,通过SQL拦截与改写实现敏感信息加密存储,解决手动处理繁琐及系统改... 目录痛点一:痛点二:脱敏配置Quick Start——Spring 显示配置:1.引入依赖2.创建脱敏

SpringBoot整合Apache Flink的详细指南

《SpringBoot整合ApacheFlink的详细指南》这篇文章主要为大家详细介绍了SpringBoot整合ApacheFlink的详细过程,涵盖环境准备,依赖配置,代码实现及运行步骤,感兴趣的... 目录1. 背景与目标2. 环境准备2.1 开发工具2.2 技术版本3. 创建 Spring Boot

Spring Boot 整合 Apache Flink 的详细过程

《SpringBoot整合ApacheFlink的详细过程》ApacheFlink是一个高性能的分布式流处理框架,而SpringBoot提供了快速构建企业级应用的能力,下面给大家介绍Spri... 目录Spring Boot 整合 Apache Flink 教程一、背景与目标二、环境准备三、创建项目 & 添

SpringBoot整合Sa-Token实现RBAC权限模型的过程解析

《SpringBoot整合Sa-Token实现RBAC权限模型的过程解析》:本文主要介绍SpringBoot整合Sa-Token实现RBAC权限模型的过程解析,本文给大家介绍的非常详细,对大家的学... 目录前言一、基础概念1.1 RBAC模型核心概念1.2 Sa-Token核心功能1.3 环境准备二、表结

MQTT SpringBoot整合实战教程

《MQTTSpringBoot整合实战教程》:本文主要介绍MQTTSpringBoot整合实战教程,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录MQTT-SpringBoot创建简单 SpringBoot 项目导入必须依赖增加MQTT相关配置编写

python多线程并发测试过程

《python多线程并发测试过程》:本文主要介绍python多线程并发测试过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、并发与并行?二、同步与异步的概念?三、线程与进程的区别?需求1:多线程执行不同任务需求2:多线程执行相同任务总结一、并发与并行?1、

MybatisPlus3.3.1整合clickhouse的过程

《MybatisPlus3.3.1整合clickhouse的过程》:本文主要介绍MybatisPlus3.3.1整合clickhouse的过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定... 前言ClickHouse是俄罗斯Yandex发布的一款数据分析型数据库支持sql语法,详情可以访问官网,