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)的更多相关文章

  1. AES加密解密通用版Object-C / C# / JAVA

    1.无向量 128位 /// <summary> /// AES加密(无向量) /// </summary> /// <param name="plainByt ...

  2. [转](.NET Core C#) AES Encryption

    本文转自:https://www.example-code.com/dotnet-core/crypt2_aes.asp Chilkat.Crypt2 crypt = new Chilkat.Cryp ...

  3. Java中List,ArrayList、Vector,map,HashTable,HashMap区别用法

    Java中List,ArrayList.Vector,map,HashTable,HashMap区别用法 标签: vectorhashmaplistjavaiteratorinteger ArrayL ...

  4. Java集合类源码解析:Vector

    [学习笔记]转载 Java集合类源码解析:Vector   引言 之前的文章我们学习了一个集合类 ArrayList,今天讲它的一个兄弟 Vector.为什么说是它兄弟呢?因为从容器的构造来说,Vec ...

  5. Java容器类List、ArrayList、Vector及map、HashTable、HashMap的区别与用法

    Java容器类List.ArrayList.Vector及map.HashTable.HashMap的区别与用法 ArrayList 和Vector是采用数组方式存储数据,此数组元素数大于实际存储的数 ...

  6. [JavaSecurity] - AES Encryption

    1. AES Algorithm The Advanced Encryption Standard (AES), also as known as Rijndael (its original nam ...

  7. too many open files linux服务器 golang java

    1. 现象 服务的cpu跑满(golang实现), 并大量报too many open files错误.服务使用systemd来运行,部署在阿里ecs上. 2.分析 从日志来看,cpu的上升主要为到达 ...

  8. LeetCode算法题-Add Strings(Java实现)

    这是悦乐书的第223次更新,第236篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第90题(顺位题号是415).给定两个非负整数num1和num2表示为字符串,返回num ...

  9. LeetCode算法题-Isomorphic Strings(Java实现)

    这是悦乐书的第191次更新,第194篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第50题(顺位题号是205).给定两个字符串s和t,确定它们是否是同构的.如果s中的字符 ...

随机推荐

  1. 创建并运行第一个Django项目

    首先, 添加Django模块: 在CMD命令行输入 python -m django --version 查看Django版本: 创建第一个Django项目: 整个工程的目录结构: mysite目录是 ...

  2. pyhon文件操作典型代码实现(非常经典!)

    1. 编写一个程序,统计当前目录下每个文件类型的文件数,程序实现如图: 实现代码: import os all_files = os.listdir(os.chdir("D:\\" ...

  3. 使用Python客户端(redis-py)连接Redis--华为云DCS for Redis使用经验

    使用Python连接Redis,需要先安装Python以及redis-py,以CentOS为例,介绍redis-py的客户端环境搭建. 第0步:准备工作 华为云上购买1台弹性云服务器ECS(我选了Ce ...

  4. 线性代数之——微分方程和 exp(At)

    本节的核心是将常系数微分方程转化为线性代数问题. \[\frac{du}{dt}=\lambda u \quad 的解为 \quad u(t) = Ce^{\lambda t}\] 代入 \(t=0\ ...

  5. HDU 3265/POJ 3832 Posters(扫描线+线段树)(2009 Asia Ningbo Regional)

    Description Ted has a new house with a huge window. In this big summer, Ted decides to decorate the ...

  6. 软工第三次作业——个人PSP

    9.22--9.26本周例行报告 1.PSP(personal software process )个人软件过程. 类型 任务 预计时间 开始时间 结束时间 中断时间 实际用时 准备工作 学习重定向 ...

  7. 词频统计 SPEC 20170914 1 1 1 1 1

    功能1 小文件输入,为表明程序能跑,结果真实而不是迫害老五,请他亲自键盘在控制台下输入命令. #include<stdio.h> #include<string.h> #inc ...

  8. ASP.NET MVC中controller和view相互传值的方式

    ASP.NET MVC中Controller向view传值的方式: ViewBag.ViewData.TempData 单个值的传递 Json 匿名类型 ExpandoObject Cookie Vi ...

  9. lintcode-184-最大数

    184-最大数 给出一组非负整数,重新排列他们的顺序把他们组成一个最大的整数. 注意事项 最后的结果可能很大,所以我们返回一个字符串来代替这个整数. #### 样例 给出 [1, 20, 23, 4, ...

  10. lintcode-143-排颜色 II

    143-排颜色 II 给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序. 注意事项 You are not ...