java 加密工具类(MD5、RSA、AES等加密方式)

2024-06-14 16:38
文章标签 java aes 工具 加密 方式 rsa md5

本文主要是介绍java 加密工具类(MD5、RSA、AES等加密方式),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.加密工具类encryption

MD5加密

import org.apache.commons.codec.digest.DigestUtils;/*** MD5加密组件* * @author wbw* @version 1.0* @since 1.0*/
public abstract class MD5Util {/*** MD5加密* * @param data*            待加密数据* @return byte[] 消息摘要* * @throws Exception*/public static byte[] encodeMD5(String data) throws Exception {// 执行消息摘要return DigestUtils.md5(data);}/*** MD5加密* * @param data*            待加密数据* @return byte[] 消息摘要* * @throws Exception*/public static String encodeMD5Hex(String data) {// 执行消息摘要return DigestUtils.md5Hex(data);}
}
AES加密:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;public class AESUtil {private static final String KEY_AES = "AES";public static String encrypt(String src, String key) throws Exception {if (key == null || key.length() != 16) {throw new Exception("key不满足条件");} byte[] raw = key.getBytes();SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);Cipher cipher = Cipher.getInstance(KEY_AES);cipher.init(Cipher.ENCRYPT_MODE, skeySpec);byte[] encrypted = cipher.doFinal(src.getBytes());return byte2hex(encrypted);}public static String decrypt(String src, String key) throws Exception {if (key == null || key.length() != 16) {throw new Exception("key不满足条件");}byte[] raw = key.getBytes();SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);Cipher cipher = Cipher.getInstance(KEY_AES);cipher.init(Cipher.DECRYPT_MODE, skeySpec);byte[] encrypted1 = hex2byte(src);byte[] original = cipher.doFinal(encrypted1);String originalString = new String(original);return originalString;}public static byte[] hex2byte(String strhex) {if (strhex == null) {return null;}int l = strhex.length();if (l % 2 == 1) {return null;}byte[] b = new byte[l / 2];for (int i = 0; i != l / 2; i++) {b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),16);}return b;}public static String byte2hex(byte[] b) {String hs = "";String stmp = "";for (int n = 0; n < b.length; n++) {stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));if (stmp.length() == 1) {hs = hs + "0" + stmp;} else {hs = hs + stmp;}}return hs.toUpperCase();}}
Base64加密:

import org.apache.commons.codec.binary.Base64;/*** Base64组件* * @author wbw* @version 1.0* @since 1.0*/
public abstract class Base64Util {/*** 字符编码*/public final static String ENCODING = "UTF-8";/*** Base64编码* * @param data 待编码数据* @return String 编码数据* @throws Exception*/public static String encode(String data) throws Exception {// 执行编码byte[] b = Base64.encodeBase64(data.getBytes(ENCODING));return new String(b, ENCODING);}/*** Base64安全编码<br>* 遵循RFC 2045实现* * @param data*            待编码数据* @return String 编码数据* * @throws Exception*/public static String encodeSafe(String data) throws Exception {// 执行编码byte[] b = Base64.encodeBase64(data.getBytes(ENCODING), true);return new String(b, ENCODING);}/*** Base64解码* * @param data 待解码数据* @return String 解码数据* @throws Exception*/public static String decode(String data) throws Exception {// 执行解码byte[] b = Base64.decodeBase64(data.getBytes(ENCODING));return new String(b, ENCODING);}}
DES加密:

import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;/*** DES安全编码组件* * @author wbw* @version 1.0*/
public abstract class DESUtil {static{Security.insertProviderAt(new BouncyCastleProvider(), 1);}/*** 密钥算法 <br>* Java 6 只支持56bit密钥 <br>* Bouncy Castle 支持64bit密钥*/public static final String KEY_ALGORITHM = "DES";/*** 加密/解密算法 / 工作模式 / 填充方式*/public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";/*** 转换密钥* * @param key*            二进制密钥* @return Key 密钥* @throws Exception*/private static Key toKey(byte[] key) throws Exception {// 实例化DES密钥材料DESKeySpec dks = new DESKeySpec(key);// 实例化秘密密钥工厂SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);// 生成秘密密钥SecretKey secretKey = keyFactory.generateSecret(dks);return secretKey;}/*** 解密* * @param data*            待解密数据* @param key*            密钥* @return byte[] 解密数据* @throws Exception*/public static byte[] decrypt(byte[] data, byte[] key) throws Exception {// 还原密钥Key k = toKey(key);// 实例化Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);// 初始化,设置为解密模式cipher.init(Cipher.DECRYPT_MODE, k);// 执行操作return cipher.doFinal(data);}/*** 加密* * @param data*            待加密数据* @param key*            密钥* @return byte[] 加密数据* @throws Exception*/public static byte[] encrypt(byte[] data, byte[] key) throws Exception {// 还原密钥Key k = toKey(key);// 实例化Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);// 初始化,设置为加密模式cipher.init(Cipher.ENCRYPT_MODE, k);// 执行操作return cipher.doFinal(data);}/*** 生成密钥 <br>* Java 6 只支持56bit密钥 <br>* Bouncy Castle 支持64bit密钥 <br>* * @return byte[] 二进制密钥* @throws Exception*/public static byte[] initKey() throws Exception {/** 实例化密钥生成器* * 若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM);* 替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC");*/KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);/** 初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64);*/kg.init(56, new SecureRandom());// 生成秘密密钥SecretKey secretKey = kg.generateKey();// 获得密钥的二进制编码形式return secretKey.getEncoded();}public static byte[] initKey(String seed) throws Exception {KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);SecureRandom secureRandom = new SecureRandom(new Base64().decode(seed));  kg.init(secureRandom);SecretKey secretKey = kg.generateKey();return secretKey.getEncoded();}
}
RSA加密:

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;import javax.crypto.Cipher;import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;/*** RSA安全编码组件* * @author wbw* @version 1.0*/
public class RSAUtil {/*** 非对称加密密钥算法*/public static final String KEY_ALGORITHM_RSA = "RSA";/*** 公钥*/private static final String RSA_PUBLIC_KEY = "RSAPublicKey";/*** 私钥*/private static final String RSA_PRIVATE_KEY = "RSAPrivateKey";/*** RSA密钥长度 * 默认1024位,* 密钥长度必须是64的倍数, * 范围在512至65536位之间。*/private static final int KEY_SIZE = 1024;static{Security.insertProviderAt(new BouncyCastleProvider(), 1);}/*** 私钥解密* * @param data*            待解密数据* @param key*            私钥* @return byte[] 解密数据* @throws Exception*/public static byte[] decryptByPrivateKey(byte[] data, byte[] key)throws Exception {// 取得私钥PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);// 生成私钥PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, privateKey);int blockSize = cipher.getBlockSize();if(blockSize>0){ByteArrayOutputStream bout = new ByteArrayOutputStream(64);int j = 0;while (data.length - j * blockSize > 0) {bout.write(cipher.doFinal(data, j * blockSize, blockSize));j++;}return bout.toByteArray();}return cipher.doFinal(data);}/*** 公钥解密* * @param data*            待解密数据* @param key*            公钥* @return byte[] 解密数据* @throws Exception*/public static byte[] decryptByPublicKey(byte[] data, byte[] key)throws Exception {// 取得公钥X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);// 生成公钥PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, publicKey);return cipher.doFinal(data);}/*** 公钥加密* * @param data*            待加密数据* @param key*            公钥* @return byte[] 加密数据* @throws Exception*/public static byte[] encryptByPublicKey(byte[] data, byte[] key)throws Exception {// 取得公钥X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, publicKey);int blockSize = cipher.getBlockSize();if(blockSize>0){int outputSize = cipher.getOutputSize(data.length);int leavedSize = data.length % blockSize;int blocksSize = leavedSize != 0 ? data.length / blockSize + 1: data.length / blockSize;byte[] raw = new byte[outputSize * blocksSize];int i = 0,remainSize=0;while ((remainSize = data.length - i * blockSize) > 0) {int inputLen = remainSize > blockSize?blockSize:remainSize;cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);i++;}return raw;}return cipher.doFinal(data);}/*** 私钥加密* * @param data*            待加密数据* @param key*            私钥* @return byte[] 加密数据* @throws Exception*/public static byte[] encryptByPrivateKey(byte[] data, byte[] key)throws Exception {// 取得私钥PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);// 生成私钥PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, privateKey);int blockSize = cipher.getBlockSize();if(blockSize>0){int outputSize = cipher.getOutputSize(data.length);int leavedSize = data.length % blockSize;int blocksSize = leavedSize != 0 ? data.length / blockSize + 1: data.length / blockSize;byte[] raw = new byte[outputSize * blocksSize];int i = 0,remainSize=0;while ((remainSize = data.length - i * blockSize) > 0) {int inputLen = remainSize > blockSize?blockSize:remainSize;cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);i++;}return raw;}return cipher.doFinal(data);}/*** 取得私钥* * @param keyMap*            密钥Map* @return key 私钥* @throws Exception*/public static Key getPrivateKey(Map<String, Key> keyMap)throws Exception {return keyMap.get(RSA_PRIVATE_KEY);}/*** 取得私钥* * @param keyMap*            密钥Map* @return byte[] 私钥* @throws Exception*/public static byte[] getPrivateKeyByte(Map<String, Key> keyMap)throws Exception {return keyMap.get(RSA_PRIVATE_KEY).getEncoded();}/*** 取得公钥* * @param keyMap*            密钥Map* @return key 公钥* @throws Exception*/public static Key getPublicKey(Map<String, Key> keyMap)throws Exception {return keyMap.get(RSA_PUBLIC_KEY);}/*** 取得公钥* * @param keyMap*            密钥Map* @return byte[] 公钥* @throws Exception*/public static byte[] getPublicKeyByte(Map<String, Key> keyMap)throws Exception {return keyMap.get(RSA_PUBLIC_KEY).getEncoded();}/*** 初始化密钥* @param byte[] seed 种子* @return Map 密钥Map* @throws Exception*/public static Map<String,Key> initKey(byte[] seed)throws Exception{// 实例化密钥对生成器KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM_RSA);// 初始化密钥对生成器keyPairGen.initialize(KEY_SIZE,	new SecureRandom(seed) );// 生成密钥对KeyPair keyPair = keyPairGen.generateKeyPair();// 公钥RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();// 私钥RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();// 封装密钥Map<String, Key> keyMap = new HashMap<String, Key>(2);keyMap.put(RSA_PUBLIC_KEY, publicKey);keyMap.put(RSA_PRIVATE_KEY, privateKey);return keyMap;}/*** 初始化密钥* @param seed 种子* @return Map 密钥Map* @throws Exception*/public static Map<String,Key> initKey(String seed)throws Exception{return initKey(seed.getBytes());}/*** 初始化密钥* * @return Map 密钥Map* @throws Exception*/public static Map<String, Key> initKey() throws Exception {return initKey(UUID.randomUUID().toString().getBytes());}public static PublicKey getPublicRSAKey(String key) throws Exception {X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.decode(key));KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);return kf.generatePublic(x509);}public static PrivateKey getPrivateRSAKey(String key) throws Exception {PKCS8EncodedKeySpec pkgs8 = new PKCS8EncodedKeySpec(Base64.decode(key));KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);return kf.generatePrivate(pkgs8);}}






这篇关于java 加密工具类(MD5、RSA、AES等加密方式)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

高效录音转文字:2024年四大工具精选!

在快节奏的工作生活中,能够快速将录音转换成文字是一项非常实用的能力。特别是在需要记录会议纪要、讲座内容或者是采访素材的时候,一款优秀的在线录音转文字工具能派上大用场。以下推荐几个好用的录音转文字工具! 365在线转文字 直达链接:https://www.pdf365.cn/ 365在线转文字是一款提供在线录音转文字服务的工具,它以其高效、便捷的特点受到用户的青睐。用户无需下载安装任何软件,只