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. Qt-QML-C++交互实现文件IO系统

    QMl是没有自己的文件IO控制的,这里如果我们需要对文件进行读写操作,那么就需要去C++或者JS完成交互,交互方式有多种,由于我还没有掌握,这里就不介绍具体的交互方式了.这里就简单说明一下我的实现过程 ...

  2. APP九宫格滑动解锁的处理

    写手机自动化测试脚本关于APP九宫格滑动解锁方面采用了appium API 之 TouchAction 操作. 先是用uiautomatorviewer.bat查询APP元素坐标: 手工计算九宫格每个 ...

  3. python基础之全局局部变量及函数参数

    1.局部变量和全局变量 1.1局部变量 局部变量是在函数内部定义的变量,只能在定义函数的内部使用 函数执行结束后,函数内部的局部变量会被系统收回 不同函数可以定义相同名字的局部变量,但是各用个的互不影 ...

  4. C if语句判断年龄

    #include <stdio.h> int main(int argc, char **argv) { //新建两个变量给变量赋值跟初始化:const int a=45;int c=0; ...

  5. [转载]启动tomcat时,一直卡在Deploying web application directory这块的解决方案

    转载:https://www.cnblogs.com/mycifeng/p/6972446.html 本来今天正常往服务器上扔一个tomcat 部署一个项目的, 最后再启动tomcat 的时候 发现项 ...

  6. [转载]Tensorflow中reduction_indices 的用法

    Tensorflow中reduction_indices 的用法 默认时None 压缩成一维

  7. sql月,年,统计报表sql报表

    select DevName as 设备名称, count(flux) as 流量数据个数, max(flux) as 流量最大值, min(flux) as 流量最小值, avg(flux) as ...

  8. 基于Hadoop2.5.0的集群搭建

    http://download.csdn.net/download/yameing/8011891 一. 规划 1.  准备安装包 JDK:http://download.oracle.com/otn ...

  9. ZOJ 3229 Shoot the Bullet(有源汇的上下界最大流)

    Description Gensokyo is a world which exists quietly beside ours, separated by a mystical border. It ...

  10. ZOJ 2532 Internship(最大流找关键割边)

    Description CIA headquarter collects data from across the country through its classified network. Th ...