AES encryption of files (and strings) in java with randomization of IV (initialization vector)
http://siberean.livejournal.com/14788.html
Java encryption-decryption examples, I've seen so far in Internet, are having IV been hard coded, i.e. not changed every time. However randomization of the initialization vector (IV) is a must for AES and for strong security (WEP was compromised because of hardcoding of IV). Notice that IV is not a "salt", and is not a secret, but like a cryptographic nonce - must be randomized each time.
In simple example below - IV is attached in the beginning of the stream.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Arrays; import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; public class Encryption { private static final int IV_LENGTH=16; /* A helper - to reuse the stream code below - if a small String is to be encrypted */
public static byte[] encrypt(String plainText, String password) throws Exception {
ByteArrayInputStream bis = new ByteArrayInputStream(plainText.getBytes("UTF8"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
encrypt(bis, bos, password);
return bos.toByteArray();
} public static byte[] decrypt(String cipherText, String password) throws Exception {
byte[] cipherTextBytes = cipherText.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(cipherTextBytes);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
decrypt(bis, bos, password);
return bos.toByteArray();
} public static void encrypt(InputStream in, OutputStream out, String password) throws Exception{ SecureRandom r = new SecureRandom();
byte[] iv = new byte[IV_LENGTH];
r.nextBytes(iv);
out.write(iv); //write IV as a prefix
out.flush();
//System.out.println(">>>>>>>>written"+Arrays.toString(iv)); Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding"); //"DES/ECB/PKCS5Padding";"AES/CBC/PKCS5Padding"
SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); out = new CipherOutputStream(out, cipher);
byte[] buf = new byte[1024];
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
out.close();
} public static void decrypt(InputStream in, OutputStream out, String password) throws Exception{ byte[] iv = new byte[IV_LENGTH];
in.read(iv);
//System.out.println(">>>>>>>>red"+Arrays.toString(iv)); Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding"); //"DES/ECB/PKCS5Padding";"AES/CBC/PKCS5Padding"
SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); in = new CipherInputStream(in, cipher);
byte[] buf = new byte[1024];
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
out.close();
} public static void copy(int mode, String inputFile, String outputFile, String password) throws Exception { BufferedInputStream is = new BufferedInputStream(new FileInputStream(inputFile));
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile));
if(mode==Cipher.ENCRYPT_MODE){
encrypt(is, os, password);
}
else if(mode==Cipher.DECRYPT_MODE){
decrypt(is, os, password);
}
else throw new Exception("unknown mode");
is.close();
os.close();
} public static void main(String[] args){ if(args.length<1){
System.out.println("Pass at least one argument (filename)");
return;
}
try{
//check files - just for safety
String fileName=args[0];
String tempFileName=fileName+".enc";
String resultFileName=fileName+".dec"; File file = new File(fileName);
if(!file.exists()){
System.out.println("No file "+fileName);
return;
}
File file2 = new File(tempFileName);
File file3 = new File(resultFileName);
if(file2.exists() || file3.exists()){
System.out.println("File for encrypted temp file or for the result decrypted file already exists. Please remove it or use a different file name");
return;
} copy(Cipher.ENCRYPT_MODE, fileName, tempFileName, "password12345678");
copy(Cipher.DECRYPT_MODE, tempFileName, resultFileName, "password12345678"); System.out.println("Success. Find encrypted and decripted files in current directory");
}
catch(Exception e){
e.printStackTrace();
}
} }
Usage:
$ javac Encryption.java
Pass any existing file, you want to encrypt through command line argument (test.sh in the following example):
$ java Encryption test.sh
Success. Find encrypted and decripted files in current directory
Encrypted file (test.enc):
$ cat test.sh.enc
&X▒b▒▒▒▒_▒▒$Z▒▒f▒XboM▒ ▒_f§R▒s▒♣▒▒K▒M;▒▒▒▒'L▒ZS◄;▒▒i
▒▒|VØ▒:?▒▒▒?▒9y{7"▒▒▒▒+▒▒e}▒▒yi▒▒y_/jjU:▒▒_▒ ►p▒?▒▒▒;\[lE▒▒▒▒Cpc▒46▒▒▒▒@▒<▒n▒↓I▒
▒▒s▒?b▒p▒O▒▒▒▒▒▒▒\d▒4n3'▒▒▒Y♦<▒▒▒▒▒▒>▒▒▒▒Ih▒▒▒´\▒↓_R▒vGW▒▒▒V▒▒?(Q♥G J◄DMS▒▒▒
zC;*
Let's check the decrypted file (test.dec):
$ cat test.sh.dec
#!/bin/sh i=0
depth=6 nodes_number=$(echo "2^$depth" | bc) #echo "total nodes: $nodes_number" while [ $i -lt $nodes_number ] ;do number=$(echo "obase=2;$i" | bc)
printf "%0${depth}o\n" 0$number
i=`expr $i + 1`
done
The file is readable.
AES encryption of files (and strings) in java with randomization of IV (initialization vector)的更多相关文章
- AES加密解密通用版Object-C / C# / JAVA
1.无向量 128位 /// <summary> /// AES加密(无向量) /// </summary> /// <param name="plainByt ...
- [转](.NET Core C#) AES Encryption
本文转自:https://www.example-code.com/dotnet-core/crypt2_aes.asp Chilkat.Crypt2 crypt = new Chilkat.Cryp ...
- Java中List,ArrayList、Vector,map,HashTable,HashMap区别用法
Java中List,ArrayList.Vector,map,HashTable,HashMap区别用法 标签: vectorhashmaplistjavaiteratorinteger ArrayL ...
- Java集合类源码解析:Vector
[学习笔记]转载 Java集合类源码解析:Vector 引言 之前的文章我们学习了一个集合类 ArrayList,今天讲它的一个兄弟 Vector.为什么说是它兄弟呢?因为从容器的构造来说,Vec ...
- Java容器类List、ArrayList、Vector及map、HashTable、HashMap的区别与用法
Java容器类List.ArrayList.Vector及map.HashTable.HashMap的区别与用法 ArrayList 和Vector是采用数组方式存储数据,此数组元素数大于实际存储的数 ...
- [JavaSecurity] - AES Encryption
1. AES Algorithm The Advanced Encryption Standard (AES), also as known as Rijndael (its original nam ...
- too many open files linux服务器 golang java
1. 现象 服务的cpu跑满(golang实现), 并大量报too many open files错误.服务使用systemd来运行,部署在阿里ecs上. 2.分析 从日志来看,cpu的上升主要为到达 ...
- LeetCode算法题-Add Strings(Java实现)
这是悦乐书的第223次更新,第236篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第90题(顺位题号是415).给定两个非负整数num1和num2表示为字符串,返回num ...
- LeetCode算法题-Isomorphic Strings(Java实现)
这是悦乐书的第191次更新,第194篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第50题(顺位题号是205).给定两个字符串s和t,确定它们是否是同构的.如果s中的字符 ...
随机推荐
- BehaviorDesigner学习
行为树: 行为树设计师插件是一个专门为unity设计的AI插件. 学习用!!!插件地址:链接:http://pan.baidu.com/s/1dF2okPN 密码:b43m 通过继承Behavior中 ...
- 前端开发工程师 - 05.产品前端架构 - 协作流程 & 接口设计 & 版本管理 & 技术选型 &开发实践
05.产品前端架构 第1章--协作流程 WEB系统 角色定义 协作流程 职责说明 第2章--接口设计 概述 接口规范 规范应用 本地开发 第3章--版本管理 见 Java开发工程师(Web方向) - ...
- jvm 语法糖
jvm 语法糖主要包括: 1. 泛型 相同擦除类型参数,返回值不同也可以编译成功, 对比方法重载矛盾. 原因:class文件格式中,只要描述符不是完全一致的两个方法就可以共存. 擦 ...
- Liunx 基本命令
find : find ./ -name "*instantiate_post_check.yml*" grep: openstack network show fe92bfcf- ...
- [ Continuously Update ] The Paper List of Image / Video Captioning
Papers Published in 2018 Convolutional Image Captioning - Jyoti Aneja et al., CVPR 2018 - [ Paper Re ...
- http://www.yiibai.com/javalang/string_endswith.html
http://www.yiibai.com/javalang/string_endswith.html
- 第十九次ScrumMeeting会议
第十九次Scrum Meeting 时间:2017/12/9 地点:三公寓大厅 人员:蔡帜 王子铭 游心 解小锐 王辰昱 李金奇 杨森 陈鑫 赵晓宇 照片: 目前工作进展 名字 今日 明天的工作 蔡帜 ...
- 第二章 shell的语法
变量:字符串.数字.环境和参数 获取变量内容可以在变量前使用$字符,使用echo指令可以将变量内容输出到终端. wuchao@wuchao-Lenovo:~$ var=hello wuchao@wuc ...
- DDL、DML和DCL的比较【引用学习】
1.DDL 1-1.DDL的概述 DDL(Data Definition Language 数据定义语言)用于操作对象和对象的属性,这种对象包括数据库本身,以 ...
- Delphi 模式窗体返回值ModalResult的使用方法及注意事项
1.基础知识简介: ModalResult是指一个模式窗体(form.showmodal)的返回值,一般用于相应窗体上按钮的ModalResult属性: 显示完窗体(关闭)后,会返回此属性预设的值做为 ...