首页 > 其他分享 >aes 加密和解密

aes 加密和解密

时间:2022-11-07 11:32:40浏览次数:88  
标签:aes return String Exception 解密 static key new 加密

package com.example.myapp.commons.utils.aes;

public class AESTester {

static String key;

static {
try {
key = AESUtils.getSecretKey();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) throws Exception {
long begin = System.currentTimeMillis();
encryptFile();
decryptFile();
test();
long end = System.currentTimeMillis();
System.err.println("耗时:" + (end-begin)/1000 + "秒");
}

static void encryptFile() throws Exception {
String sourceFilePath = "D:/aa/11.txt";
String destFilePath = "D:/aa/en_11.txt";
AESUtils.encryptFile(key, sourceFilePath, destFilePath);
}

static void decryptFile() throws Exception {
String sourceFilePath = "D:/aa/en_11.txt";
String destFilePath = "D:/aa/de_11.txt";
AESUtils.decryptFile(key, sourceFilePath, destFilePath);
}

static void test() throws Exception {
String source = "这是一行测试DES加密/解密的文字,你看完也等于没看,是不是啊?!";
System.err.println("原文:\t" + source);
byte[] inputData = source.getBytes();
inputData = AESUtils.encrypt(inputData, key);
System.err.println("加密后:\t" + Base64Util.encode(inputData));
byte[] outputData = AESUtils.decrypt(inputData, key);
String outputStr = new String(outputData);
System.err.println("解密后:\t" + outputStr);
}

}



package com.example.myapp.commons.utils.aes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
* <p>
* AES加密解密工具包
* </p>
*
* @author IceWee
* @date 2012-5-18
* @version 1.0
*/
public class AESUtils {

private static final String ALGORITHM = "AES";
private static final int KEY_SIZE = 128;
private static final int CACHE_SIZE = 1024;

/**
* <p>
* 生成随机密钥
* </p>
*
* @return
* @throws Exception
*/
public static String getSecretKey() throws Exception {
return getSecretKey(null);
}

/**
* <p>
* 生成密钥
* </p>
*
* @param seed 密钥种子
* @return
* @throws Exception
*/
public static String getSecretKey(String seed) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
SecureRandom secureRandom;
if (seed != null && !"".equals(seed)) {
secureRandom = new SecureRandom(seed.getBytes());
} else {
secureRandom = new SecureRandom();
}
keyGenerator.init(KEY_SIZE, secureRandom);
SecretKey secretKey = keyGenerator.generateKey();
return Base64Util.encode(secretKey.getEncoded());
}

/**
* <p>
* 加密
* </p>
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String key) throws Exception {
Key k = toKey(Base64Util.decode(key));
byte[] raw = k.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(data);
}

/**
* <p>
* 文件加密
* </p>
*
* @param key
* @param sourceFilePath
* @param destFilePath
* @throws Exception
*/
public static void encryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {
File sourceFile = new File(sourceFilePath);
File destFile = new File(destFilePath);
if (sourceFile.exists() && sourceFile.isFile()) {
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
Key k = toKey(Base64Util.decode(key));
byte[] raw = k.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
CipherInputStream cin = new CipherInputStream(in, cipher);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = cin.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
cin.close();
in.close();
}
}

/**
* <p>
* 解密
* </p>
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, String key) throws Exception {
Key k = toKey(Base64Util.decode(key));
byte[] raw = k.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(data);
}

/**
* <p>
* 文件解密
* </p>
*
* @param key
* @param sourceFilePath
* @param destFilePath
* @throws Exception
*/
public static void decryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {
File sourceFile = new File(sourceFilePath);
File destFile = new File(destFilePath);
if (sourceFile.exists() && sourceFile.isFile()) {
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
FileInputStream in = new FileInputStream(sourceFile);
FileOutputStream out = new FileOutputStream(destFile);
Key k = toKey(Base64Util.decode(key));
byte[] raw = k.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
CipherOutputStream cout = new CipherOutputStream(out, cipher);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
cout.write(cache, 0, nRead);
cout.flush();
}
cout.close();
out.close();
in.close();
}
}

/**
* <p>
* 转换密钥
* </p>
*
* @param key
* @return
* @throws Exception
*/
private static Key toKey(byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
return secretKey;
}

}

package com.example.myapp.commons.utils.aes;



import java.io.UnsupportedEncodingException;
import java.util.Base64;


public class Base64Util {

/**
* 将字符串转为Base64编码
*
* @param a
* @return
*/
public static String encode(String a) {
final Base64.Encoder encoder = Base64.getEncoder();
byte[] textByte;
try {
textByte = a.getBytes("UTF-8");
return encoder.encodeToString(textByte);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}

public static String encode(byte[] textByte) {
final Base64.Encoder encoder = Base64.getEncoder();
try {
return encoder.encodeToString(textByte);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

// /**
// * 将 Base64编码串转换为字符串
// *
// * @param a
// * @return
// */
// public static String decode(String a) {
// final Base64.Decoder decoder = Base64.getDecoder();
// try {
// return new String(decoder.decode(a), "UTF-8");
// } catch (Exception e) {
// e.printStackTrace();
// }
// return a;
// }

/**
* 将 Base64编码串转换为字符串
*
* @param a
* @return
*/
public static byte[] decode(String a) {
final Base64.Decoder decoder = Base64.getDecoder();
try {
return decoder.decode(a);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
测试结果

原文: 这是一行测试DES加密/解密的文字,你看完也等于没看,是不是啊?!
加密后: DzP8IxJD5RnOeeJYc8ZpMChOD/r/rIMElhliDJxAkRvoeLCOa62aIP0r9cVo315BRCeCy+MwTbpXhSqb+O/XgXkm2UI9sdqGCITufcoQdMhVEoFI8v3O/c545Jg0ztlv
解密后: 这是一行测试DES加密/解密的文字,你看完也等于没看,是不是啊?!
耗时:0秒

标签:aes,return,String,Exception,解密,static,key,new,加密
From: https://blog.51cto.com/u_15862653/5828366

相关文章

  • RabitMQ密码是否加密的说明
    操作说明:用附件的platform-middleware-stream-0.0.4-SNAPSHOT.jar,可针对现场的密码生成密文,然后将密文配置到监管的配置文件就可以了。cd到jar包所在目录位置并执行......
  • js中变量base64加密传输
    首先对base64进行定义:varBase64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){......
  • RSA加密算法
    RSA加密算法概述    RSA算法是一种经典的非对称加密算法,密钥一般由三个数字构成:N、E、D。对于一些信息,我们总有办法将其转化为数字,设该数字为X,对应的密文是Y。则......
  • NEO与以太坊:为什么NEO可能是2018年最强的加密货币
    NEO,它可以与以太坊竞争吗?NEO和以太坊你会下重注投资其中的哪一个? 2013年年末,以太坊创始人VitalikButerin(V神)发布了以太坊初版白皮书,启动了项目。2014年7月24日起,以太坊......
  • Openssl Des3对压缩文件进行加密命令详解
    群友提问:致力于明天:tar-cvf-WMG_Back_"$Today"|openssldes3-salt-khY91gd3GJAAfghECleLwWQAPGK9Cxs-out$dir_backup_today.tar.des3致力于明天:有人懂这个......
  • 使用 Java 类生成 MD5 加密字符
    MD5常用于密码加密,例如,在注册时可以将密码转为MD5再放入数据库,在登录时校验登录密码和数据库存放的加密密码是否一致,来保证密码在数据库中存储的安全性。下面介绍使用......
  • P8814 [CSP-J 2022] 解密
    P8814[CSP-J2022]解密//ni=pi*qi//ei*di=pi*qi-pi-qi+2//ei*di=ni-pi-qi+2//pi+qi=ni-ei*di+2//pi*qi=ni//pi......
  • 【网安】第一次写的简单加密程序
    教学链接:https://www.bilibili.com/video/BV1UG411L74y?p=33&vd_source=01e5c1103fb910315f88a7bdc747b3d5c语言实现的简单加密程序核心加密原理:将文件逐字符读取和密码......
  • 19、对数字进行加密
    题目:输入num为四位数,对其加密规则如下:  1.每一位数分别加5,然后将其替换为该数除以10取余的结果  2.将该数的第一位和第四位互换,第二位与第三位互换  3.最后合......
  • 学习笔记——base标签、加密方式、JDBC、将java中添加的数据增加到数据库中
    2022-11-03一、base标签1、作用:用于添加web项目的前缀。2、放置位置:放置在head标签内部,一般放在首行。3、使用方式:<basehref="/项目名称/">,在html网页中的其他(例如:图......