AES加密是一种对称加密方式(何为对称加密可以百度),加密工具已经被集成于jdk中,所以开发时不必再导入第三方jar.
加密/解密中需要秘钥key,就是说解密一份AES加密过的文件需要使用和加密时相同的key. key可以是128位的,也可以是256位的,上代码:
/**
* 用password生成key
* @param password 用来生成key的字符串,加密解密同一份文件要使用相同的key
*
* */
private SecretKeySpec getKeys(String password) {
int keyLength = 256; //根据需要可以设置成128位或者256位
byte[] keyBytes = new byte[keyLength / 16];
Arrays.fill(keyBytes, (byte) 0x0);
byte[] passwordBytes = new byte[0];
SecretKeySpec key = null;
try {
passwordBytes = password.getBytes("UTF-8");
int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
key = new SecretKeySpec(keyBytes, "AES");
;
} catch (Exception e) {
e.printStackTrace();
}
return key;
}
加密和解密的过程也非常简单:
/**
* <p>
* 文件加密
* </p>
*
* @param sourceFilePath
* @param destFilePath
* @throws Exception
*/
public boolean encryptFile(String sourceFilePath, String destFilePath) {
File sourceFile = new File(sourceFilePath);
File destFile = new File(destFilePath);
try {
if (sourceFile.exists() && sourceFile.isFile()) {
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, getKeys(Constant.AES_KEY));
CipherInputStream cin = new CipherInputStream(in, cipher);
byte[] cache = new byte[1024];
int nRead = 0;
while ((nRead = cin.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
cin.close();
in.close();
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* <p>
* 文件解密
* </p>
*
* @param sourceFilePath
* @param destFilePath
* @throws Exception
*/
public void decryptFile(String sourceFilePath, String destFilePath) throws Exception {
File sourceFile = new File(sourceFilePath);
File destFile = new File(destFilePath);
if (sourceFile.exists() && sourceFile.isFile()) {
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
FileInputStream in = new FileInputStream(sourceFile);
FileOutputStream out = new FileOutputStream(destFile);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, getKeys(Constant.AES_KEY));
CipherOutputStream cout = new CipherOutputStream(out, cipher);
byte[] cache = new byte[1024];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
cout.write(cache, 0, nRead);
cout.flush();
}
cout.close();
out.close();
in.close();
}
}
其中使用的常量大家可以自行定义.
demo下载地址: http://download.youkuaiyun.com/download/qq_40983782/10111384
demo使用了一位博主的部分部分代码,只是后来找不到这位博主的博客了,在此一并致谢.
在demo里我是先把一份本地的文件复制到sdCard,然后在同一个文件夹下生成加密和解密的文件,效果如下:
如果读者在开发过程中发现有什么问题可以联系本人 odm.lee@foxmail.com