数字信封(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

相关文章

Spring Boot 整合 SSE(Server-Sent Events)实战案例(全网最全)

《SpringBoot整合SSE(Server-SentEvents)实战案例(全网最全)》本文通过实战案例讲解SpringBoot整合SSE技术,涵盖实现原理、代码配置、异常处理及前端交互,... 目录Spring Boot 整合 SSE(Server-Sent Events)1、简述SSE与其他技术的对

Java整合Protocol Buffers实现高效数据序列化实践

《Java整合ProtocolBuffers实现高效数据序列化实践》ProtocolBuffers是Google开发的一种语言中立、平台中立、可扩展的结构化数据序列化机制,类似于XML但更小、更快... 目录一、Protocol Buffers简介1.1 什么是Protocol Buffers1.2 Pro

springboot整合mqtt的步骤示例详解

《springboot整合mqtt的步骤示例详解》MQTT(MessageQueuingTelemetryTransport)是一种轻量级的消息传输协议,适用于物联网设备之间的通信,本文介绍Sprin... 目录1、引入依赖包2、yml配置3、创建配置4、自定义注解6、使用示例使用场景:mqtt可用于消息发

基于Python实现数字限制在指定范围内的五种方式

《基于Python实现数字限制在指定范围内的五种方式》在编程中,数字范围限制是常见需求,无论是游戏开发中的角色属性值、金融计算中的利率调整,还是传感器数据处理中的异常值过滤,都需要将数字控制在合理范围... 目录引言一、基础条件判断法二、数学运算巧解法三、装饰器模式法四、自定义类封装法五、NumPy数组处理

基于Python Playwright进行前端性能测试的脚本实现

《基于PythonPlaywright进行前端性能测试的脚本实现》在当今Web应用开发中,性能优化是提升用户体验的关键因素之一,本文将介绍如何使用Playwright构建一个自动化性能测试工具,希望... 目录引言工具概述整体架构核心实现解析1. 浏览器初始化2. 性能数据收集3. 资源分析4. 关键性能指

SpringBoot实现RSA+AES自动接口解密的实战指南

《SpringBoot实现RSA+AES自动接口解密的实战指南》在当今数据泄露频发的网络环境中,接口安全已成为开发者不可忽视的核心议题,RSA+AES混合加密方案因其安全性高、性能优越而被广泛采用,本... 目录一、项目依赖与环境准备1.1 Maven依赖配置1.2 密钥生成与配置二、加密工具类实现2.1

SpringBoot整合Dubbo+ZK注册失败的坑及解决

《SpringBoot整合Dubbo+ZK注册失败的坑及解决》使用Dubbo框架时,需在公共pom添加依赖,启动类加@EnableDubbo,实现类用@DubboService替代@Service,配... 目录1.先看下公共的pom(maven创建的pom工程)2.启动类上加@EnableDubbo3.实

SpringBoot整合(ES)ElasticSearch7.8实践

《SpringBoot整合(ES)ElasticSearch7.8实践》本文详细介绍了SpringBoot整合ElasticSearch7.8的教程,涵盖依赖添加、客户端初始化、索引创建与获取、批量插... 目录SpringBoot整合ElasticSearch7.8添加依赖初始化创建SpringBoot项

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap