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中的字符 ...
随机推荐
- C 判断成绩是否及格
#include <stdio.h> int main(int argc, char **argv) { // 新建两个变量 pass代表及格分数的固定变量 score代表学生成绩的一个 ...
- lintcode514 栅栏染色
栅栏染色 我们有一个栅栏,它有n个柱子,现在要给柱子染色,有k种颜色可以染.必须保证不存在超过2个相邻的柱子颜色相同,求有多少种染色方案. 注意事项 n和k都是非负整数 您在真实的面试中是否遇到过这个 ...
- (转)CGMA - Organic World Building in UE4: week 6
原文:丢失,这篇是艺术家博客上发现的,小道整理笔记中,临时放于效果案例目录. In this week we focused on creating the grass and flora t ...
- 【转载】appium 操作汇总
'''.appium api第二弹 锋利的python,这是初稿,2015/1/5 如有错误的地方,请同学们进行留言,我会及时予以修改,尽量整合一份ok的api 作者:Mads Spiral QQ:7 ...
- 【第六章】MySQL日志文件管理
1.日志文件管理概述: 配置文件:/etc/my.cnf 作用:MySQL日志文件是用来记录MySQL数据库客户端连接情况.SQL语句的执行情况以及错误信息告示. 分类:MySQL日志文件分为4种:错 ...
- Python入门(4)
一.while循环 有时候,你可能需要计算机来帮重复做一件事,这时就需要循环. while condition: statements (else: statements ) 当condition条件 ...
- POJ 3498 March of the Penguins(网络最大流)
Description Somewhere near the south pole, a number of penguins are standing on a number of ice floe ...
- Redis+Keepalived高可用方案详细分析
背景 目前,Redis集群的官方方案还处在开发测试中,未集成到稳定版中.且目前官方开发中的Redis Cluster提供的功能尚不完善(可参考官方网站或http://www.redisdoc.com/ ...
- java报错:Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE
Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE at org.apache.http.conn.ss ...
- 安装配置erlang_db_driver
erlang-db-driver是北京融易通公司开源的一个erlang支持众多数据库的一个驱动类库,据其wiki介绍,其支持MySQL, Oracle, Sybase, DB2 and Informi ...