学习Java AES加解密字符串和文件方法,然后写个简单工具类
Reference Core Java Volume Ⅱ 10th Edition
1 对称加密
“Java密码扩展”包含了一个Cipher,它是所有密码算法的超类。通过getInstance(algorithmName)可以获得一个密码对象。
cipher.init(mode, key);模式有以下四种:
Cipher.ENCRYPT;
Cipher.DECRYPT;
Cipher.WRAP_MODE和Cipher.UNWRAP_MODE会用一个秘钥对另一个秘钥进行加密
// 可以一直调用cipher.update(),进行加密
int blockSize = cipher.getBlockSize();
byte[] inBytes = new byte[blockSize];
... // read inBytes
int outputSize = cipher.getOutputSize(blockSize);
byte[] outBytes = new byte[outputSize];
int outLength = cipher.update(inBytes, 0, outputSize, outBytes);
... // write outBytes
//完成上述操作后,最后必须调用doFinal返回加密后的数据
//如果最后一个输入数据块小于blockSize:
outBytes = cipher.doFinal(inBytes, 0, inLength);
//如果所有数据都已加密:
outBytes = cipher.doFinal();
//如果输入数组长度不够blockSize,update方法返回的数组为空,长度为0
doFinal调用时必要的,因为它会对最后的数据块进行填充,常用填充方案是RSA Security公司在公共秘钥密码标准#5(Public Key Cryptography Standard, PKCS)中描述的方案
该方案最后一个数据块不是全用0填充,而是等于填充字节数量的值最为填充值
2 秘钥生成
我们需要确保秘钥生成时随机的。这需要遵循下面的步骤:
1). 为加密算法获取KeyGenerator
2). 用随机源来初始化秘钥发生器。如果密码长度是可变的,还需要指定期望的密码块长度
3). 调用generateKey方法
例如:
KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
keygen.init(random);
SecretKey key = keygen.generateKey();
或者可以从一组固定的原生数据(也许是口令或者随机键产生的)中生成一个密钥,这时可以使用SecretKeyFactory
byte[] keyData = ...; // 16 byte for AES
SecretKey key = new SecretKeySpec(keyData, "AES");
如果要生成密钥,必须使用“真正的随机”数。例如,在常见的Random中的常规的随即发生器。是根据当前的日期和时间来产生的,因此它不够随机。假设计算机时钟可以精确到1/10秒,那么每天最多存在864000个种子。如果攻击者知道密钥的日期(通常可以由消息日期或证书有效日期推算出来),那么就可以很容易的产生那一天的所有可能的种子。
SecureRandom类产生的随机数,远比由Random类产生的那些随机数字安全得多。也可以由我们提供种子。由setSeed(byre[] b)方法传递给它。
如果没有随机数发生器提供种子,那么它将通过启动线程,是他们睡眠,然后测量他们被唤醒的准确时间,一次来计算自己的20个字节的种子
!注意: 这个算法仍然被人为是安全的。而且,在过去,依靠对诸如硬盘访问之间的类的其他计算机组件进行计时的算法, 后来也被证明不也是完全随机的。
3 密码流
密码流能够透明地调用update和doFinal方法,所以非常方便,源码也很简单。
API javax.crypto.CipherInputStream 1.4
CipherInputStream(InputStream in, Cipher cipher)
构建一个输入流,读取in中的数据,并且使用指定的密码对数据进行解密和加密。int read()int read(byte[] b, int off, int len)
读取输入流中的数据,该数据会被自动解密和加密
API javax.crypto.CipherOutputStream 1.4
CipherOutputSream(OutputStream out, Cipher cipher)
构建一个输出流,以便将数据写入out,并且使用指定的秘密对数据进行加密和解密。void write(int ch)void write(byte b, int off, int len)
将数据写入输出流,该数据会被自动加密和解密。void flush()
刷新密码缓冲区,如果需要的化,执行填充操作。
CipherInputStream.read读取完数据后,如果不够一个数据块,会自动调用doFinal方法填充后返回
CipherOutputStream.close方法如果发现,还有没写完的数据,会调用doFinal方法返回数据然后输出
4 工具类
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;
import java.util.Objects;
/**
* 加解密字符串、文件工具类
* @author YYang 13047
* @version 2022/10/25 12:10
*/
public class AESUtils {
public static final String AES = "AES";
//PKCS: Public Key Cryptographic Standard
public static final String AES_ECB = "AES/ECB/PKCS5Padding";
public static final String AES_CBC = "AES/CBC/PKCS5Padding";
public static final String AES_CFB = "AES/CFB/PKCS5Padding";
public static final int KEY_SIZE = 128;
public static final int BUFFER_SIZE = 512;
public static String encodeToString(byte[] unEncoded) {
return Base64.getEncoder().encodeToString(unEncoded);
}
public static byte[] decode(String encoded) {
return Base64.getDecoder().decode(encoded);
}
public static String generateAESKey() throws NoSuchAlgorithmException {
return generateAESKey(KEY_SIZE, null);
}
/**
* @param keySize keySize must be equal to 128, 192 or 256;
* @param seed 随机数种子
* @see #generateAESKey0()
*/
public static String generateAESKey(int keySize, String seed) throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance(AES);
SecureRandom random = (seed == null || seed.length() == 0) ?
new SecureRandom() : new SecureRandom(seed.getBytes(StandardCharsets.UTF_8));
//如果不初始化,SunJCE默认使用new SecureRandom()
keyGen.init(keySize, random);
SecretKey secretKey = keyGen.generateKey();
return encodeToString(secretKey.getEncoded());
}
/**
* @return 密钥,不初始化,使用默认的
*/
public static String generateAESKey0() throws NoSuchAlgorithmException {
return encodeToString(KeyGenerator.getInstance(AES).generateKey().getEncoded());
}
/**
* @param algorithm 算法名
* @return 返回一个当前算法BlockSize大小的随机数组,然后Base64转码
* @see #generateAESIv()
*/
public static String generateAESIv(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher cipher = Cipher.getInstance(algorithm);
int blockSize = cipher.getBlockSize();
byte[] ivByte = new byte[blockSize];
new SecureRandom().nextBytes(ivByte);
return encodeToString(ivByte);
}
public static String generateAESIv() {
//AES blockSize == 16
byte[] bytes = new byte[16];
new SecureRandom().nextBytes(bytes);
return encodeToString(bytes);
}
public static AlgorithmParameterSpec getIv(String ivStr) {
if (ivStr == null || ivStr.length() < 1) return null;
return new IvParameterSpec(decode(ivStr));
}
/**
* @return 指定秘钥和算法,返回Key对象
*/
public static Key getKey(String keyStr, String algorithm) {
return new SecretKeySpec(decode(keyStr), algorithm);
}
public static Cipher initCipher(String algorithm, int cipherMode, Key key, AlgorithmParameterSpec param)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
Cipher cipher = Cipher.getInstance(algorithm);
if (param == null) {
cipher.init(cipherMode, key);
} else {
cipher.init(cipherMode, key, param);
}
return cipher;
}
public static String encrypt(String algorithm, String keyStr, String ivStr, String unencryptedStr) throws Exception {
return encrypt(algorithm, keyStr, ivStr, unencryptedStr, StandardCharsets.UTF_8);
}
public static String encrypt(String algorithm, String keyStr, String ivStr, String unencryptedStr, Charset charset) throws Exception {
Cipher cipher = initCipher(algorithm, Cipher.ENCRYPT_MODE, getKey(keyStr, AES), getIv(ivStr));
byte[] encrypted = cipher.doFinal(unencryptedStr.getBytes(charset));
return encodeToString(encrypted);
}
public static String decrypt(String algorithm, String keyStr, String ivStr, String encryptedStr) throws Exception {
return decrypt(algorithm, keyStr, ivStr, encryptedStr, StandardCharsets.UTF_8);
}
public static String decrypt(String algorithm, String keyStr, String ivStr, String encryptedStr, Charset charset) throws Exception {
Cipher cipher = initCipher(algorithm, Cipher.DECRYPT_MODE, getKey(keyStr, AES), getIv(ivStr));
byte[] decrypted = cipher.doFinal(decode(encryptedStr));
return new String(decrypted, charset);
}
/**
* 解密文件
*/
public static void encryptFile(String algorithm, String keyStr, String ivStr, File source, File target) throws Exception {
checkPath(source, target);
Cipher cipher = initCipher(algorithm, Cipher.ENCRYPT_MODE, getKey(keyStr, AES), getIv(ivStr));
try (FileOutputStream fos = new FileOutputStream(target);
CipherInputStream cis = new CipherInputStream(new FileInputStream(source), cipher)) {
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = cis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
}
}
/**
* 加密文件
*/
public static void decryptFile(String algorithm, String keyStr, String ivStr, File source, File target) throws Exception {
checkPath(source, target);
Cipher cipher = initCipher(algorithm, Cipher.DECRYPT_MODE, getKey(keyStr, AES), getIv(ivStr));
try (FileInputStream fis = new FileInputStream(source);
CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(target), cipher)) {
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = fis.read(buffer)) != -1) {
cos.write(buffer, 0, len);
}
cos.flush();
}
}
public static void checkPath(File source, File target) throws IOException {
Objects.requireNonNull(source);
Objects.requireNonNull(target);
if (source.isDirectory() || !source.exists()) {
throw new FileNotFoundException(source.toString());
}
if (Objects.equals(source.getCanonicalPath(), target.getCanonicalPath())) {
throw new IllegalArgumentException("sourceFile equals targetFile");
}
File parentDirectory = target.getParentFile();
if (parentDirectory != null && !parentDirectory.exists()) {
Files.createDirectories(parentDirectory.toPath());
}
}
public static void main(String[] args) throws Exception {
System.out.println(generateAESKey());
System.out.println(generateAESIv(AES_ECB));
String keyStr = "dN2VIV86Z2ShT47pEC1XwQ==";
String ivStr = "00hDTDhCxa9t11TrQSso3w==";
String encrypted = encrypt(AES_CBC, keyStr, ivStr, "中国深圳");
System.out.println("encrypted:" + encrypted);
System.out.println(decrypt(AES_CBC, keyStr, ivStr, encrypted));
File source = new File("README.md");
File encryptedFile = new File("out/README1.md");
File decryptedFile = new File("out/README2.md");
encryptFile(AES_CBC, keyStr, ivStr, source, encryptedFile);
decryptFile(AES_CBC, keyStr, ivStr, encryptedFile, decryptedFile);
}
}
学习Java AES加解密字符串和文件方法,然后写个简单工具类的更多相关文章
- java AES加解密
AES加解密工具类 package com.yan.demo; import org.apache.commons.lang3.StringUtils; import sun.misc.BASE64D ...
- 记一次Java AES 加解密 对应C# AES加解密 的一波三折
最近在跟三方对接 对方采用AES加解密 作为一个资深neter Ctrl CV 是我最大的优点 所以我义正言辞的问他们要了demo java demo代码: public class EncryptD ...
- JAVA Aes加解密详解
上篇随笔留了一个问题,两种加密结果不一样? 其实是内部实现方式不一样,具体见注释 /** * 提供密钥和向量进行加密 * * @param sSrc * @param key * @param iv ...
- Java 使用AES/CBC/PKCS7Padding 加解密字符串
介于java 不支持PKCS7Padding,只支持PKCS5Padding 但是PKCS7Padding 和 PKCS5Padding 没有什么区别要实现在java端用PKCS7Padding填充, ...
- C# RSA加解密与验签,AES加解密,以及与JAVA平台的密文加解密
前言: RSA算法是利用公钥与密钥对数据进行加密验证的一种算法.一般是拿私钥对数据进行签名,公钥发给友商,将数据及签名一同发给友商,友商利用公钥对签名进行验证.也可以使用公钥对数据加密,然后用私钥对数 ...
- 两种JavaScript的AES加密方式(可与Java相互加解密)
由于JavaScript属于弱类型脚本语言,因此当其与强类型的后台语言进行数据交互时会产生各种问题,特别是加解密的操作.本人由于工作中遇到用js与Java进行相互加解密的问题,在网上查了很多资料及代码 ...
- Java中的AES加解密工具类:AESUtils
本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.constants.SysConsta ...
- AES加解密异常java.security.InvalidKeyException: Illegal key size
AES加解密异常 Java后台AES解密,抛出异常如下:java.security.InvalidKeyException: Illegal key size Illegal key size or ...
- Java、C#双语版配套AES加解密示例
这年头找个正经能用的东西那是真难,网上一搜索一大堆,正经能用的没几个,得,最后还是得靠自己,正巧遇上需要AES加解密的地方了,而且还是Java和C#间的相互加解密操作,这里做个备忘 这里采用的加解 ...
随机推荐
- ceph 004 纠删码池 修改参数 cephx认证
复习ceph003 存储池为逻辑概念,存储池可以占用整个集群的所有空间 [root@ceph01 ~]# ceph osd pool create pool1 pool 'pool1' created ...
- POJ2559/HDU1506 Largest Rectangle in a Histogram (cartesian tree)
Die datenstruktur ist erataunlich! #include <iostream> #include <cstdio> #include <cs ...
- 长篇图解java反射机制及其应用场景
一.什么是java反射? 在java的面向对象编程过程中,通常我们需要先知道一个Class类,然后new 类名()方式来获取该类的对象.也就是说我们需要在写代码的时候(编译期或者编译期之前)就知道我们 ...
- React报错之You provided a `checked` prop to a form field
正文从这开始~ 总览 当我们在多选框上设置了checked 属性,却没有onChange 处理函数时,会产生"You provided a checked prop to a form fi ...
- 渗透攻防Web篇-深入浅出SQL注入
1 背景 京东SRC(Security Response Center)收录大量外部白帽子提交的sql注入漏洞,漏洞发生的原因多为sql语句拼接和Mybatis使用不当导致. 2 手工检测 2.1 前 ...
- 三 单例模式【Singleton Pattern】 来自CBF4LIFE 的设计模式
这个模式是很有意思,而且比较简单,但是我还是要说因为它使用的是如此的广泛,如此的有人缘,单例就是单一.独苗的意思,那什么是独一份呢?你的思维是独一份,除此之外还有什么不能山寨的呢?我们举个比较难复制的 ...
- ASP.NET Core 6框架揭秘实例演示[35]:利用Session保留语境
客户端和服务器基于HTTP的消息交换就好比两个完全没有记忆能力的人在交流,每次单一的HTTP事务体现为一次"一问一答"的对话.单一的对话毫无意义,在在同一语境下针对某个主题进行的多 ...
- KingbaseES R6 集群repmgr.conf参数'recovery'测试案例(三)
案例三:测试'recovery = manual' 1.查看集群节点状态信息: [kingbase@node1 bin]$ ./repmgr cluster show ID | Name | Role ...
- shell脚本自动化部署Zabbix4.2(修改脚本替换版本)
#!/bin/bash # 检查操作系统版本,该脚本只能运行在 Centos 7.x 系统上 cat /etc/redhat-release |grep -i centos |grep '7.[[:d ...
- python 基于aiohttp的异步爬虫实战
钢铁知识库,一个学习python爬虫.数据分析的知识库.人生苦短,快用python. 之前我们使用requests库爬取某个站点的时候,每发出一个请求,程序必须等待网站返回响应才能接着运行,而在整个爬 ...