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加解密字符串和文件方法,然后写个简单工具类的更多相关文章

  1. java AES加解密

    AES加解密工具类 package com.yan.demo; import org.apache.commons.lang3.StringUtils; import sun.misc.BASE64D ...

  2. 记一次Java AES 加解密 对应C# AES加解密 的一波三折

    最近在跟三方对接 对方采用AES加解密 作为一个资深neter Ctrl CV 是我最大的优点 所以我义正言辞的问他们要了demo java demo代码: public class EncryptD ...

  3. JAVA Aes加解密详解

    上篇随笔留了一个问题,两种加密结果不一样? 其实是内部实现方式不一样,具体见注释 /** * 提供密钥和向量进行加密 * * @param sSrc * @param key * @param iv ...

  4. Java 使用AES/CBC/PKCS7Padding 加解密字符串

    介于java 不支持PKCS7Padding,只支持PKCS5Padding 但是PKCS7Padding 和 PKCS5Padding 没有什么区别要实现在java端用PKCS7Padding填充, ...

  5. C# RSA加解密与验签,AES加解密,以及与JAVA平台的密文加解密

    前言: RSA算法是利用公钥与密钥对数据进行加密验证的一种算法.一般是拿私钥对数据进行签名,公钥发给友商,将数据及签名一同发给友商,友商利用公钥对签名进行验证.也可以使用公钥对数据加密,然后用私钥对数 ...

  6. 两种JavaScript的AES加密方式(可与Java相互加解密)

    由于JavaScript属于弱类型脚本语言,因此当其与强类型的后台语言进行数据交互时会产生各种问题,特别是加解密的操作.本人由于工作中遇到用js与Java进行相互加解密的问题,在网上查了很多资料及代码 ...

  7. Java中的AES加解密工具类:AESUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.constants.SysConsta ...

  8. AES加解密异常java.security.InvalidKeyException: Illegal key size

    AES加解密异常 Java后台AES解密,抛出异常如下:java.security.InvalidKeyException: Illegal key size Illegal key size or ...

  9. Java、C#双语版配套AES加解密示例

      这年头找个正经能用的东西那是真难,网上一搜索一大堆,正经能用的没几个,得,最后还是得靠自己,正巧遇上需要AES加解密的地方了,而且还是Java和C#间的相互加解密操作,这里做个备忘 这里采用的加解 ...

随机推荐

  1. mybatis 08: 返回主键值的insert操作 + 利用UUID获取字符串(了解)

    返回主键值的insert操作 应用背景 图示说明 在上述业务背景下,涉及两张数据表的关联操作:用户表 + 用户积分表 传统操作:在对用户表执行完插入语句后,再次查询该用户的uid,将该uid作为外键, ...

  2. 【AGC】集成华为AGC崩溃服务实用教程

    ​简介 AppGallery Connect(简称AGC)崩溃服务提供了轻量级崩溃分析服务,集成Crash SDK,可以实现零代码快速集成,您的应用能够在崩溃时自动收集崩溃报告,帮助您了解应用版本质量 ...

  3. Express 使用 Cookie

    在使用 Cookie 之前,需要给 Express 加载中间件,cookie-parser: npm i cookie-parser Express 使用中间件: import express fro ...

  4. {版本发布公告}HMS Core 6.6.0来啦

    分析服务 ◆ 留存分析支持¬将流失用户存为受众,开发者通过对流失人群的分层以及多维分析,在制定相关用户召回策略时将更有针对性: ◆ 原"受众分析"更名为"人群洞察&quo ...

  5. 算法模板:spfa

    #include<iostream> #include<algorithm> #include<cstring> #include<string> #i ...

  6. vue2和vue3的区别?

    vue2和vue3的主要区别在于以下几点: 1.生命周期函数钩子不同 2.数据双向绑定原理不同 3.定义变量和方法不同 4.指令和插槽的使用不同 5.API类型不同 6.是否支持碎片 7.父子组件之间 ...

  7. MySQL递归查询语法

    业务上有一个递归查询数据表进行累加计算的需求,实现方式上有函数.SQL语句等多种方式,最后选择了SQL方式,如下: <select id="selectChildren" p ...

  8. 【android 逆向】arm if

    #include <stdio.h> void if1(int n){ //if else语句 if(n < 10){ printf("the number less th ...

  9. 玩转Configmap配置应用的各种姿势

    在 k8s 中使用配置主要可以有以下几种方式来实现: 1. 向容器传递命令行参数 2. 为每个容器指定自定义的环境变量 3. 通过特殊类型的卷将配置文件挂载到容器中 在 k8s 中覆盖命令行参数 和 ...

  10. SQL语句中过滤条件放在on和where子句中的区别和联系

    摘要: 介绍在多表关联SQL语句中,过滤条件放在on和where子句中的区别--inner join中没区别,外连接就不一样. 综述   蚂蚁金服的一道SQL面试题如下:SQL语句中,过滤条件放在on ...