AES工具加密

2024-06-01 01:48
文章标签 aes 工具 加密

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



AES加密类


package com.pohoocredit.profitcard.backend.utils;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* @desc:
* @Author:li_shuai
* @date:Create on 2017/9/15 16:25
*/
public class AESEncipher {
/**
* AES加密字符串
*
* @param content
*            需要被加密的字符串
* @param salt
*            加密需要的密码
* @return 密文
*/
public static byte[] encrypt(String content, String salt) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
kgen.init(128, new SecureRandom(salt.getBytes()));// 利用用户密码作为随机数初始化出
// 128位的key生产者
//加密没关系,SecureRandom是生成安全随机数序列,salt.getBytes()是种子,只要种子相同,序列就一样,所以解密只要有password就行
SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥
byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥,如果此密钥不支持编码,则返回
// null。
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);// 加密
return result;
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 解密AES加密过的字符串
*
* @param content
*            AES加密过过的内容
* @param salt
*            加密时的密码
* @return 明文
*/
public static byte[] decrypt(byte[] content, String salt) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
kgen.init(128, new SecureRandom(salt.getBytes()));
SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥
byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
byte[] result = cipher.doFinal(content);
return result; // 明文
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将加密后的返回结果进行base编码
* @param content
* @param salt
* @return
*/
public static String encodeSecretKey(String content,String salt) {
byte[] bytes = AESEncipher.encrypt(content, salt);
return Base64Encipher.encodeToStr(bytes);
}
/**
* 将base64编码的结果返回,转码为加密前的结果
* @param content
* @param salt
* @return
*/
public static String decodeSecretKey(String content,String salt) {
byte[] decode = Base64Encipher.decode(content);
byte[] decrypt = AESEncipher.decrypt(decode, salt);
return new String(decrypt);
}
public static void main(String... args) {
System.out.println(AESEncipher.encodeSecretKey("123456你好", "kuaixin"));
System.out.println(AESEncipher.decodeSecretKey("fCog/HjpMlQtQrOWbxKL7g==","kuaixin"));
}
}



Base64类


package com.pohoocredit.profitcard.backend.utils;
import java.io.*;
/**
* @desc:
* @Author:li_shuai
* @date:Create on 2017/9/15 17:17
*/
public class Base64Encipher {
public Base64Encipher() {
}
/**
* 功能:编码字符串
*
* @author 
* @date 2017年09月13日
* @param data
*  源字符串
* @return String
*/
public static String encodeToStr(byte[] data) {
return new String(encode(data));
}
/**
* 功能:解码字符串
*
* @author 
* @date 2017年09月13日
* @param data
*  源字符串
* @return String
*/
public static byte[] decode(String data) {
return decode(data.toCharArray());
}
/**
* 功能:编码byte[]
*
* @author 
* @date 2017年09月13日
* @param data
*  源
* @return char[]
*/
public static char[] encode(byte[] data) {
char[] out = new char[((data.length + 2) / 3) * 4];
for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
boolean quad = false;
boolean trip = false;
int val = (0xFF & (int) data[i]);
val <<= 8;
if ((i + 1) < data.length) {
val |= (0xFF & (int) data[i + 1]);
trip = true;
}
val <<= 8;
if ((i + 2) < data.length) {
val |= (0xFF & (int) data[i + 2]);
quad = true;
}
out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 1] = alphabet[val & 0x3F];
val >>= 6;
out[index + 0] = alphabet[val & 0x3F];
}
return out;
}
/**
* 功能:解码
*
* @author 
* @date 2017年09月13日
* @param data
*  编码后的字符数组
* @return byte[]
*/
public static byte[] decode(char[] data) {
int tempLen = data.length;
for (int ix = 0; ix < data.length; ix++) {
if ((data[ix] > 255) || codes[data[ix]] < 0) {
--tempLen; // ignore non-valid chars and padding
}
}
// calculate required length:
// -- 3 bytes for every 4 valid base64 chars
// -- plus 2 bytes if there are 3 extra base64 chars,
// or plus 1 byte if there are 2 extra.
int len = (tempLen / 4) * 3;
if ((tempLen % 4) == 3) {
len += 2;
}
if ((tempLen % 4) == 2) {
len += 1;
}
byte[] out = new byte[len];
int shift = 0; // # of excess bits stored in accum
int accum = 0; // excess bits
int index = 0;
// we now go through the entire array (NOT using the 'tempLen' value)
for (int ix = 0; ix < data.length; ix++) {
int value = (data[ix] > 255) ? -1 : codes[data[ix]];
if (value >= 0) { // skip over non-code
accum <<= 6; // bits shift up by 6 each time thru
shift += 6; // loop, with new bits being put in
accum |= value; // at the bottom.
if (shift >= 8) { // whenever there are 8 or more shifted in,
shift -= 8; // write them out (from the top, leaving any
out[index++] = // excess at the bottom for next iteration.
(byte) ((accum >> shift) & 0xff);
}
}
}
// if there is STILL something wrong we just have to throw up now!
if (index != out.length) {
throw new Error("Miscalculated data length (wrote " + index
+ " instead of " + out.length + ")");
}
return out;
}
/**
* 功能:编码文件
*
* @author 
* @date 2017年09月13日
* @param file
*  源文件
*/
public static void encode(File file) throws IOException {
if (!file.exists()) {
System.exit(0);
}
else {
byte[] decoded = readBytes(file);
char[] encoded = encode(decoded);
writeChars(file, encoded);
}
file = null;
}
/**
* 功能:解码文件。
*
* @author 
* @date 2017年09月13日
* @param file
*  源文件
* @throws IOException
*/
public static void decode(File file) throws IOException {
if (!file.exists()) {
System.exit(0);
} else {
char[] encoded = readChars(file);
byte[] decoded = decode(encoded);
writeBytes(file, decoded);
}
file = null;
}
//
// code characters for values 0..63
//
private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
.toCharArray();
//
// lookup table for converting base64 characters to value in range 0..63
//
private static byte[] codes = new byte[256];
static {
for (int i = 0; i < 256; i++) {
codes[i] = -1;
// LoggerUtil.debug(i + "&" + codes[i] + " ");
}
for (int i = 'A'; i <= 'Z'; i++) {
codes[i] = (byte) (i - 'A');
// LoggerUtil.debug(i + "&" + codes[i] + " ");
}
for (int i = 'a'; i <= 'z'; i++) {
codes[i] = (byte) (26 + i - 'a');
// LoggerUtil.debug(i + "&" + codes[i] + " ");
}
for (int i = '0'; i <= '9'; i++) {
codes[i] = (byte) (52 + i - '0');
// LoggerUtil.debug(i + "&" + codes[i] + " ");
}
codes['+'] = 62;
codes['/'] = 63;
}
private static byte[] readBytes(File file) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = null;
InputStream fis = null;
InputStream is = null;
try {
fis = new FileInputStream(file);
is = new BufferedInputStream(fis);
int count = 0;
byte[] buf = new byte[16384];
while ((count = is.read(buf)) != -1) {
if (count > 0) {
baos.write(buf, 0, count);
}
}
b = baos.toByteArray();
} finally {
try {
if (fis != null)
fis.close();
if (is != null)
is.close();
if (baos != null)
baos.close();
} catch (Exception e) {
System.out.println(e);
}
}
return b;
}
private static char[] readChars(File file) throws IOException {
CharArrayWriter caw = new CharArrayWriter();
Reader fr = null;
Reader in = null;
try {
fr = new FileReader(file);
in = new BufferedReader(fr);
int count = 0;
char[] buf = new char[16384];
while ((count = in.read(buf)) != -1) {
if (count > 0) {
caw.write(buf, 0, count);
}
}
} finally {
try {
if (caw != null)
caw.close();
if (in != null)
in.close();
if (fr != null)
fr.close();
} catch (Exception e) {
System.out.println(e);
}
}
return caw.toCharArray();
}
private static void writeBytes(File file, byte[] data) throws IOException {
OutputStream fos = null;
OutputStream os = null;
try {
fos = new FileOutputStream(file);
os = new BufferedOutputStream(fos);
os.write(data);
} finally {
try {
if (os != null)
os.close();
if (fos != null)
fos.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
private static void writeChars(File file, char[] data) throws IOException {
Writer fos = null;
Writer os = null;
try {
fos = new FileWriter(file);
os = new BufferedWriter(fos);
os.write(data);
} finally {
try {
if (os != null)
os.close();
if (fos != null)
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// /
// end of test code.
// /
}

这篇关于AES工具加密的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

揭秘未来艺术:AI绘画工具全面介绍

📑前言 随着科技的飞速发展,人工智能(AI)已经逐渐渗透到我们生活的方方面面。在艺术创作领域,AI技术同样展现出了其独特的魅力。今天,我们就来一起探索这个神秘而引人入胜的领域,深入了解AI绘画工具的奥秘及其为艺术创作带来的革命性变革。 一、AI绘画工具的崛起 1.1 颠覆传统绘画模式 在过去,绘画是艺术家们通过手中的画笔,蘸取颜料,在画布上自由挥洒的创造性过程。然而,随着AI绘画工

墨刀原型工具-小白入门篇

墨刀原型工具-小白入门篇 简介 随着互联网的发展和用户体验的重要性越来越受到重视,原型设计逐渐成为了产品设计中的重要环节。墨刀作为一款原型设计工具,以其简洁、易用的特点,受到了很多设计师的喜爱。本文将介绍墨刀原型工具的基本使用方法,以帮助小白快速上手。 第一章:认识墨刀原型工具 1.1 什么是墨刀原型工具 墨刀是一款基于Web的原型设计工具,可以帮助设计师快速创建交互原型,并且可以与团队

大学湖北中医药大学法医学试题及答案,分享几个实用搜题和学习工具 #微信#学习方法#职场发展

今天分享拥有拍照搜题、文字搜题、语音搜题、多重搜题等搜题模式,可以快速查找问题解析,加深对题目答案的理解。 1.快练题 这是一个网站 找题的网站海量题库,在线搜题,快速刷题~为您提供百万优质题库,直接搜索题库名称,支持多种刷题模式:顺序练习、语音听题、本地搜题、顺序阅读、模拟考试、组卷考试、赶快下载吧! 2.彩虹搜题 这是个老公众号了 支持手写输入,截图搜题,详细步骤,解题必备

Windows/macOS/Linux 安装 Redis 和 Redis Desktop Manager 可视化工具

本文所有安装都在macOS High Sierra 10.13.4进行,Windows安装相对容易些,Linux安装与macOS类似,文中会做区分讲解 1. Redis安装 1.下载Redis https://redis.io/download 把下载的源码更名为redis-4.0.9-source,我喜欢跟maven、Tomcat放在一起,就放到/Users/zhan/Documents

OpenCompass:大模型测评工具

大模型相关目录 大模型,包括部署微调prompt/Agent应用开发、知识库增强、数据库增强、知识图谱增强、自然语言处理、多模态等大模型应用开发内容 从0起步,扬帆起航。 大模型应用向开发路径:AI代理工作流大模型应用开发实用开源项目汇总大模型问答项目问答性能评估方法大模型数据侧总结大模型token等基本概念及参数和内存的关系大模型应用开发-华为大模型生态规划从零开始的LLaMA-Factor

简鹿文件批量重命名:一款文件批量改名高手都在用的工具

作为 IT 行业的搬砖民工,互联网的数据量爆炸性增长,文件管理成为了一项日益重要的任务。"简鹿文件批量重命名"应运而生,旨在为用户提供一个高效、灵活的解决方案,以应对繁琐的文件命名、排序、创建及属性修改等挑战。 这款软件凭借其一键式操作、强大的自定义规则导入、以及全面的批量处理能力,极大地简化了文件管理流程,尤其适合处理大量文件的个人用户及企业环境,是提高工作效率、保持文件系统整洁的得力助手

如何用外呼工具和CRM管理系统形成销售闭环

使用外呼工具和CRM管理系统形成销售闭环是一个系统性的过程,它涉及客户数据的整合、个性化的营销活动、销售与市场活动的协作、顾客行为的追踪与理解以及营销成效的评估与优化等多个环节。 以下是如何将外呼工具和CRM管理系统有效结合以形成销售闭环的步骤: 1. 客户数据的整合与分析    - 外呼工具在与客户进行初步沟通时,会收集到客户的基本信息和初步需求。    - 这些信息随后被输入到CRM管

ASP.Net.WebAPI和工具PostMan

1.WebAPI概述 1.1 WebAPI WebAPI 是一种传统的方式,用于构建和暴露 RESTUI风格的Web服务。它提供了丰富的功能和灵活性,可以处理各种HTTP请求,并支持各种数据格式,如JSON、XML等。 WebAPI使用控制器(Controllers)和动作方法(ActionMethods)的概念、通过路由配置将请求映射到相应的方法上。 开发人员可以使用各种属性和过滤器来处

Java实现MD5加密总结

Java实现MD5加密总结 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿! 1. 什么是MD5加密 MD5是一种常用的哈希算法,用于将任意长度的数据通过哈希运算转换为固定长度的数据串,通常为128位的二进制串,常用于对密码等敏感信息进行加密存储或传输。 2. Java实现MD5加密的方法 2.1 使用java.sec

使用XmlPullParser制作BindView工具

在之前我写过了一个BindView的工具,之前使用的最要是正则表达的文本分析做的。最近,工作我认识了Android的XML解析,我又想起了这个问题。发现这个问题,其实用XmlPullParser更好解决。所以我重新写了这个工具。简单多了,而且不用格式化代码。 先分析一下如何写,简易思路如下 Created with Raphaël 2.1.0 输入文本路径 读取x