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. 怎么设计好移动APP测试用例

    软件测试工作中我们需要不断的储备和总结自己的知识和经验,怎么设计好移动APP测试用例?如:手机.平板.智能设备,并在特定网络环境下. 我们需要关注的功能点,容易出错的位置,这将对我们整个测试过程起着至 ...

  2. 即刻开始使用Kotlin开发Android的12个原因(KAD 30)

    作者:Antonio Leiva 时间:Jul, 11, 2017 原文链接:https://antonioleiva.com/reasons-kotlin-android/ 这组文章已到最后了,它们 ...

  3. 各种对list,string操作函数的总结

    #encoding=utf-8#reverse,用来反转lista=['aa','bb','cc']a.reverse()print a#['cc', 'bb', 'aa']#不能直接print a. ...

  4. Linux命令应用大词典-第41章 MySQL数据库

    41.1 mysqld_safe:MySQL服务器启动脚本 41.2 mysql_install_db:初始化MySQL数据目录 41.3 mysqlshow:显示MySQL数据库结构 41.4 my ...

  5. leetcode-第k个排列(Java和c++版)

    第k个排列 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列. 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: "123" " ...

  6. 爬虫2.2-scrapy框架-文件写入

    目录 scrapy框架-文件写入 1. lowb写法 2. 高端一点的写法 3. 优化版本 scrapy框架-文件写入 1. lowb写法 ~pipelines.py 前提回顾,spider.py中 ...

  7. Vuejs 实现简易 todoList 功能 与 组件

    todoList 结合之前 Vuejs 基础与语法 使用 v-model 双向绑定 input 输入内容与数据 data 使用 @click 和 methods 关联事件 使用 v-for 进行数据循 ...

  8. win10下搭建私链

    首先要下载geth,下载地址:https://gethstore.blob.core.windows.net/builds/geth-windows-amd64-1.7.0-6c6c7b2a.exe ...

  9. C语言struct中的长度可变数组(Flexible array member)

    C_struct中的长度可变数组(Flexible array member) Flexible array member is a feature introduced in the C99 sta ...

  10. 四:ResourceManger Restart

    概述: RM是yarn中最重要的组件.但是只有一个RM,因此存在单点失败的问题.RM的重启有两种方式: 1.(Non-work-preserving RM restart) 不保留工作状态的重启   ...