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

相关文章

捷瑞数字业绩波动性明显:关联交易不低,募资必要性遭质疑

《港湾商业观察》施子夫 5月22日,山东捷瑞数字科技股份有限公司(以下简称,捷瑞数字)及保荐机构国新证券披露第三轮问询的回复,继续推进北交所上市进程。 从2023年6月递表开始,监管层已下发三轮审核问询函,关注到捷瑞数字存在同业竞争、关联交易、募资合理性、期后业绩波动等焦点问题。公司的上市之路多少被阴影笼罩。​ 业绩波动遭问询 捷瑞数字成立于2000年,公司是一家以数字孪生驱动的工

数据时代的数字企业

1.写在前面 讨论数据治理在数字企业中的影响和必要性,并介绍数据治理的核心内容和实践方法。作者强调了数据质量、数据安全、数据隐私和数据合规等方面是数据治理的核心内容,并介绍了具体的实践措施和案例分析。企业需要重视这些方面以实现数字化转型和业务增长。 数字化转型行业小伙伴可以加入我的星球,初衷成为各位数字化转型参考库,星球内容每周更新 个人工作经验资料全部放在这里,包含数据治理、数据要

将一维机械振动信号构造为训练集和测试集(Python)

从如下链接中下载轴承数据集。 https://www.sciencedirect.com/science/article/pii/S2352340918314124 import numpy as npimport scipy.io as sioimport matplotlib.pyplot as pltimport statistics as statsimport pandas

剑指offer(C++)--和为S的两个数字

题目 输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。 class Solution {public:vector<int> FindNumbersWithSum(vector<int> array,int sum) {vector<int> result;int len = array.size();if(

剑指offer(C++)--数组中只出现一次的数字

题目 一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。 class Solution {public:void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {int len = data.size();if(len<2)return;int one = 0;for(int i

神经网络第四篇:推理处理之手写数字识别

到目前为止,我们已经介绍完了神经网络的基本结构,现在用一个图像识别示例对前面的知识作整体的总结。本专题知识点如下: MNIST数据集图像数据转图像神经网络的推理处理批处理  MNIST数据集          mnist数据图像 MNIST数据集由0到9的数字图像构成。像素取值在0到255之间。每个图像数据都相应地标有“7”、“2”、“1”等数字标签。MNIST数据集中,

江西电信联合实在智能举办RPA数字员工培训班,培养“人工智能+”电信人才

近日,江西电信与实在智能合作的2024年数字员工开发应用培训班圆满闭幕。包括省公司及11个分公司的核心业务部门,超过40名学员积极报名参与此次培训,江西电信企业信息化部门总监徐建军出席活动并致辞,风控支撑室主任黄剑主持此次培训活动。 在培训会开幕仪式上,徐建军强调,科创是电信企业发展的核心动力,学习RPA技术是实现数字化转型的关键,他阐述了RPA在提高效率、降低成本和优化资源方面的价值,并鼓励学

LeetCode —— 只出现一次的数字

只出现一次的数字 I  本题依靠异或运算符的特性,两个相同数据异或等于0,数字与0异或为本身即可解答。代码如下: class Solution {public:int singleNumber(vector<int>& nums) {int ret = 0;for (auto e : nums){ret ^= e;}return ret;}};  只出现一次的数字 II

JavaWeb 学习笔记 spring+jdbc整合开发初步

JdbcTemplate类是Spring的核心类之一,可以在org.springframework.jdbc.core中找到它。JdbcTemplate类在内部已经处理数据库的建立和释放,可以避免一些常见的错误。JdbcTemplate类可直接通过数据源的应用实例化,然后在服务中使用,也可在xml配置中作为JavaBean应用给服务使用直接上一个实例步骤1.xml配置 <?xml version

IIS10和Tomcat8整合

在网上找了很久,也试了很多,都没有弄好。后来根据这个博客,做一些小修小改,终于成功了。 我是从里面的IIS与TOMCAT整合那里开始看的。第一步上面要创建一个注册表,我没有创建。我是创建了一个名为“isapi_redirect.properties”的文件,放进tomcat安装目录的conf文件夹里面。里面内容为: # Configuration file for the Jakarta