Java常用的加密技术

项目结构:

见红框内。

总体代码:

package VirtualUtils;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Random;
public class CryptoUtils {private static final String ENCODE="utf-8";private static final String ALGORITHM="AES";private static final String PATTERN="AES/ECB/PKCS5PADDING";private static final String ALLCHAR="0123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM";public static String GenerateKey(){StringBuffer buffer=new StringBuffer();Random random=new Random();for (int i = 0; i < 16; i++) {buffer.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));}return buffer.toString();}public static int GenerateIntKey(){Random random=new Random();return random.nextInt(999999999);}public static String encrypt_msg(String txt,String key) throws Exception {SecretKey secretKey=new SecretKeySpec(key.getBytes(ENCODE),ALGORITHM);Cipher cipher=Cipher.getInstance(PATTERN);cipher.init(Cipher.ENCRYPT_MODE,secretKey);byte[] encrypt_data= cipher.doFinal(txt.getBytes(ENCODE));return Base64.getEncoder().encodeToString(encrypt_data);}public static String decrypt_msg(String txt,String key) throws Exception {SecretKey secretKey=new SecretKeySpec(key.getBytes(ENCODE),ALGORITHM);Cipher cipher=Cipher.getInstance(PATTERN);cipher.init(Cipher.DECRYPT_MODE,secretKey);byte[] decrypt_data= cipher.doFinal(Base64.getDecoder().decode(txt));return new String(decrypt_data, ENCODE);}public static byte[] Encrypt_MD5(byte[]data) throws NoSuchAlgorithmException {MessageDigest digest=MessageDigest.getInstance("MD5");digest.update(data);return digest.digest();}public static byte[] Encrypt_SHA(byte[]data) throws NoSuchAlgorithmException {MessageDigest digest=MessageDigest.getInstance("SHA");digest.update(data);return digest.digest();}public static KeyPairGenerator generator;public static KeyPair keyPair;public static final class keystore{public byte[] public_key;public byte[] private_key;}static {try {generator=KeyPairGenerator.getInstance("RSA");generator.initialize(2048);keyPair=generator.generateKeyPair();}catch (Exception err){err.printStackTrace();}}public static keystore get_key_pair(){keystore key_value=new keystore();key_value.public_key=keyPair.getPublic().getEncoded();key_value.private_key=keyPair.getPrivate().getEncoded();return key_value;}public static byte[] encrypt_data_by_public(byte[] msg, byte[] key) throws Exception {KeyFactory keyFactory=KeyFactory.getInstance("RSA");X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(key);PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec);Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE,publicKey);return cipher.doFinal(msg);}public static byte[] decrypt_data_by_private(byte[] msg, byte[] key) throws Exception{KeyFactory keyFactory=KeyFactory.getInstance("RSA");PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(key);PrivateKey privateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE,privateKey);return cipher.doFinal(msg);}public static byte[] encrypt_data_by_private(byte[] msg, byte[] key) throws Exception{KeyFactory keyFactory=KeyFactory.getInstance("RSA");PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(key);PrivateKey privateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE,privateKey);return cipher.doFinal(msg);}public static byte[] decrypt_data_by_public(byte[] msg,byte[] key) throws Exception{KeyFactory keyFactory=KeyFactory.getInstance("RSA");X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(key);PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec);Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE,publicKey);return cipher.doFinal(msg);}public static String Base64ToString(byte[]data){return Base64.getEncoder().encodeToString(data);}public static String BytesToString(byte[]data,String encode) throws UnsupportedEncodingException {return new String(data,encode);}
}

代码组成:

单向加密:sha散列加密
public static byte[] Encrypt_SHA(byte[]data) throws NoSuchAlgorithmException {MessageDigest digest=MessageDigest.getInstance("SHA");digest.update(data);return digest.digest();}
单向加密:md5散列加密
public static byte[] Encrypt_MD5(byte[]data) throws NoSuchAlgorithmException {MessageDigest digest=MessageDigest.getInstance("MD5");digest.update(data);return digest.digest();}
对称加密:AES加密
private static final String ENCODE="utf-8";private static final String ALGORITHM="AES";private static final String PATTERN="AES/ECB/PKCS5PADDING";private static final String ALLCHAR="0123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM";
public static String encrypt_msg(String txt,String key) throws Exception {SecretKey secretKey=new SecretKeySpec(key.getBytes(ENCODE),ALGORITHM);Cipher cipher=Cipher.getInstance(PATTERN);cipher.init(Cipher.ENCRYPT_MODE,secretKey);byte[] encrypt_data= cipher.doFinal(txt.getBytes(ENCODE));return Base64.getEncoder().encodeToString(encrypt_data);}public static String decrypt_msg(String txt,String key) throws Exception {SecretKey secretKey=new SecretKeySpec(key.getBytes(ENCODE),ALGORITHM);Cipher cipher=Cipher.getInstance(PATTERN);cipher.init(Cipher.DECRYPT_MODE,secretKey);byte[] decrypt_data= cipher.doFinal(Base64.getDecoder().decode(txt));return new String(decrypt_data, ENCODE);}
非对称加密:RSA加密
public static KeyPairGenerator generator;public static KeyPair keyPair;public static final class keystore{public byte[] public_key;public byte[] private_key;}static {try {generator=KeyPairGenerator.getInstance("RSA");generator.initialize(2048);keyPair=generator.generateKeyPair();}catch (Exception err){err.printStackTrace();}}public static keystore get_key_pair(){keystore key_value=new keystore();key_value.public_key=keyPair.getPublic().getEncoded();key_value.private_key=keyPair.getPrivate().getEncoded();return key_value;}public static byte[] encrypt_data_by_public(byte[] msg, byte[] key) throws Exception {KeyFactory keyFactory=KeyFactory.getInstance("RSA");X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(key);PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec);Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE,publicKey);return cipher.doFinal(msg);}public static byte[] decrypt_data_by_private(byte[] msg, byte[] key) throws Exception{KeyFactory keyFactory=KeyFactory.getInstance("RSA");PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(key);PrivateKey privateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE,privateKey);return cipher.doFinal(msg);}public static byte[] encrypt_data_by_private(byte[] msg, byte[] key) throws Exception{KeyFactory keyFactory=KeyFactory.getInstance("RSA");PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(key);PrivateKey privateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE,privateKey);return cipher.doFinal(msg);}public static byte[] decrypt_data_by_public(byte[] msg,byte[] key) throws Exception{KeyFactory keyFactory=KeyFactory.getInstance("RSA");X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(key);PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec);Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE,publicKey);return cipher.doFinal(msg);}
随机数生成(字符串):
public static String GenerateKey(){StringBuffer buffer=new StringBuffer();Random random=new Random();for (int i = 0; i < 16; i++) {buffer.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));}return buffer.toString();}
随机数生成(整形):
public static int GenerateIntKey(){Random random=new Random();return random.nextInt(999999999);}
Base64编码转字符串:
public static String Base64ToString(byte[]data){return Base64.getEncoder().encodeToString(data);}
字节数组转字符串:
public static String BytesToString(byte[]data,String encode) throws UnsupportedEncodingException {return new String(data,encode);}

代码测试:

import VirtualUtils.CryptoUtils;
public class Main {public static void main(String[]args) throws Exception {String msg="This is a test";CryptoUtils.keystore keystore=CryptoUtils.get_key_pair();byte[] en=CryptoUtils.encrypt_data_by_public(msg.getBytes("utf-8"),keystore.public_key);System.out.println(CryptoUtils.Base64ToString(CryptoUtils.decrypt_data_by_private(en,keystore.private_key)));System.out.println(new String(CryptoUtils.decrypt_data_by_private(en,keystore.private_key)));byte[] en1=CryptoUtils.encrypt_data_by_private(msg.getBytes("utf-8"),keystore.private_key);System.out.println(CryptoUtils.Base64ToString(en1));System.out.println(CryptoUtils.BytesToString(CryptoUtils.decrypt_data_by_public(en1,keystore.public_key),"utf-8"));}
}

测试结果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/618501.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

深入浅出线程原理

Linux 中的线程本质 线程接口由 Native POSIX Thread Library 提供&#xff0c;即&#xff1a;NPTL 库函数 线程被称为轻量级进程 (Light Weight Process) 每一个线程在内核中都对应一个调度实体&#xff0c;拥有独立的结构体 (task_struct) 内核设计&#xff1a;一个进程对…

【python】matplotlib画图常用功能汇总

目录: 一、matplotlib画图风格二、matplotlib图像尺寸和保存分辨率三、matplotlib子图相关功能创建子图&#xff1a;绘制子图&#xff1a;设置子图属性&#xff1a;调整布局&#xff1a;示例代码&#xff1a; 四、matplotlib字体设置字体族和字体的区别字体选择和设置1. Matplo…

Kubernetes实战(十六)-k8s节点打标签

pod可以根据调度策略让pod调度到想要的节点上运行&#xff0c;或者不在某节点运行。 1 查看现有节点运行环境已有标签 $ kubectl get nodes --show-labels NAME STATUS ROLES AGE VERSION LABELS ops-master-1 Ready control-plane,ma…

亚马逊云科技 WAF 部署小指南(五):在客户端集成 Amazon WAF SDK 抵御 DDoS 攻击...

方案介绍 在 WAF 部署小指南&#xff08;一&#xff09;中&#xff0c;我们了解了 Amazon WAF 的原理&#xff0c;并通过创建 WEB ACL 和托管规则防护常见的攻击。也了解了通过创建自定义规则在 HTTP 请求到达应用之前判断是阻断还是允许该请求。在 Amazon WAF 自定义规则中&am…

代码随想录算法训练营29期Day17|LeetCode 110,257,404

文档讲解&#xff1a;代码随想录 110.平衡二叉树 题目链接&#xff1a;https://leetcode.cn/problems/balanced-binary-tree/description/ 思路&#xff1a; 本题要求我们判断二叉树每个节点 的左右两个子树的高度差的绝对值是否超过 1。我们很容易就能想到利用dfs去做&#…

水果音乐编曲软件 FL Studio v21.2.2.3914 中文免费版(附中文设置教程)

FL studio21中文别名水果编曲软件&#xff0c;是一款全能的音乐制作软件&#xff0c;包括编曲、录音、剪辑和混音等诸多功能&#xff0c;让你的电脑编程一个全能的录音室&#xff0c;它为您提供了一个集成的开发环境&#xff0c;使用起来非常简单有效&#xff0c;您的工作会变得…

【书生·浦语】大模型实战营——第四课作业

教程文档&#xff1a;https://github.com/InternLM/tutorial/blob/main/xtuner/self.md 基础作业需要构建数据集&#xff0c;微调模型&#xff0c;让其明白自己的弟位&#xff08;OvO&#xff01;&#xff09; 微调环境准备 进入开发机后&#xff0c;先bash&#xff0c;再创…

Vue模板的理解和使用

Vue模板 Vue.js 的模板是一种声明性的语法&#xff0c;用于将数据渲染进 DOM&#xff08;文档对象模型&#xff09;。它们使开发者能够以直观的方式声明式地描述用户界面应该如何根据应用程序数据的变化动态显示。 Vue模板的主要特点包括&#xff1a; 数据绑定&#xff1a; …

列表解析与快速排序

排序是在对文本、数值等数据进行操作时常用的功能&#xff0c;本文介绍两种常用的排序方式&#xff0c;借此学习列表解析&#xff0c;并巩固递归算法。 1 选择排序 说到排序&#xff0c;以数值为例&#xff0c;肯定涉及到值大小的对比&#xff0c;选择排序即通过依次在子集中…

蓝桥杯 python 第二题 数列排序

这里给出一种解法 """ # 错的 n int(input()) dp[int(i) for i in input().split(" ")] dp.sort() print(" ".join(str(i) for i in dp)) """#这个是对的 num int(input())l list(map(int, input().split()))l.sort()pr…

AI文本生图模型Stable Diffusion部署教程

本文基于CentOS8进行Stable Diffusion开源框架部署. 1. DNS配置(但是今天出现了偶尔无法下载问题) 为了加速Github访问,我在本机配置如下 (sd) [rootshenjian stable-diffusion-webui]# cat /etc/hosts 127.0.0.1 shenjian localhost localhost.localdomain localhost4 loca…

SpringCloud openFeign 之 获取被调用服务名

SpringCloud openFeign 之 获取被调用服务名 一. 概述 低版本 feign 只能获取到被调用方法的信息。 只有高版本 feign 才支持获取到被调用服务的信息。 二. 代码实现 package com.zxguan.springcloud2.template.user;import com.zxguan.springcloud2.template.user.config…

修改权限控制(chmod命令、chown命令)

1.chmod命令 功能&#xff1a;修改文件、文件夹权限&#xff08;注意&#xff0c;只有文件、文件夹的所属用户或root用户可以修改&#xff09; 语法&#xff1a;chmod [-R] 权限 参数 权限&#xff0c;要设置的权限&#xff0c;比如755&#xff0c;表示&#xff1a;rwxr-xr-x…

Crow:蓝图路由2 Blueprint::register_blueprint

Crow:蓝图路由1 CROW_BP_ROUTE-CSDN博客 介绍了蓝图路由主要的一个作用就是将路由划分成蓝图路由根目录,然后再在蓝图路由创建子路由。 蓝图路由其实还可以在其下注册新的子蓝图路由,从而实现子目录的继续划分: crow::Blueprint bp("bp_prefix", "cstat&q…

【WPF.NET开发】WPF中的XAML资源

本文内容 使用 XAML 中的资源静态和动态资源静态资源动态资源样式、DataTemplate 和隐式键 资源是可以在应用中的不同位置重复使用的对象。 资源的示例包括画笔和样式。 本概述介绍如何使用 Extensible Application Markup Language (XAML) 中的资源。 你还可以使用代码创建和…

考研经验总结——数学篇

文章目录 一、前言二、刷题情况三、学习方法 一、前言 我是考数一的&#xff0c;我想想&#xff0c;我是从10月中旬正式开始准备考研&#xff0c;期间的话&#xff0c;跟的机构&#xff0c;没看武忠祥、没看张宇&#xff0c;什么名师的课程都没看。全程网课都是看一个老师&…

【面试突击】生产部署面试实战

&#x1f308;&#x1f308;&#x1f308;&#x1f308;&#x1f308;&#x1f308;&#x1f308;&#x1f308; 欢迎关注公众号&#xff08;通过文章导读关注&#xff1a;【11来了】&#xff09;&#xff0c;及时收到 AI 前沿项目工具及新技术 的推送 发送 资料 可领取 深入理…

C程序训练:大数相乘与阶乘的计算

两个大数相乘&#xff0c;我们可以利用小学生列竖式做乘法的方法编写程序即可。例如&#xff0c;计算123*23&#xff0c;可以按以下步骤做&#xff1a; 1. answer 0&#xff1b; 2. temp123*3 369 3. answer answer temp 4. temp 123 * 20 2460 5. answer answer t…

如何从电脑找回/恢复误删除的照片

按 Shift Delete 以后会后悔吗&#xff1f;想要恢复已删除的照片吗&#xff1f;好吧&#xff0c;如果是这样的话&#xff0c;那么您来对地方了。在本文中&#xff0c;我们将讨论如何从 PC 中检索已删除的文件。 自从摄影的概念被曝光以来&#xff0c;人们就对它着迷。早期的照…