前言:最近一直在搞DES加解密传文件数据流。在网上搜了N多资料,但是总是不太理想。
最后找到了这篇博文:http://www.oschina.net/question/54100_35081 确实不错,启发很大。
不多说贴个Android加解密的工具类:
package com.example.cryptographic;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class CryptographicUtils {
public static ByteArrayInputStream encryptDES(String filePath, String encryptKey, byte iv[])
throws Exception {
// IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
File file = new File(filePath);
FileInputStream inStream = new FileInputStream(file);
byte[] cbuf = new byte[1024];
byte[] fileByte = new byte[0];
byte[] temp;
int readLen = 0;
int tmpoffset = 0;
while ((readLen = inStream.read(cbuf)) > 0) {
tmpoffset += readLen;
temp = fileByte;
fileByte = new byte[tmpoffset];
System.arraycopy(temp, 0, fileByte, 0, temp.length);
System.arraycopy(cbuf, 0, fileByte, temp.length, readLen);
}
inStream.close();
byte[] encryptedData = cipher.doFinal(fileByte);
return new ByteArrayInputStream(encryptedData);
}
public static void decryptDES(String filePath, BufferedInputStream byteArrayStream,
String decryptKey, byte iv[]) throws Exception {
// byte[] byteMi = new Base64().decode(decryptString);
IvParameterSpec zeroIv = new IvParameterSpec(iv);
// IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
SecretKeySpec key = new SecretKeySpec(subarray(decryptKey.getBytes("UTF-8"), 0, 8), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
File file = new File(filePath);
if (!file.exists()) {
file.exists();
}
FileOutputStream outStream = new FileOutputStream(file);
byte[] cbuf = new byte[1024];
byte[] fileByte = new byte[0];
byte[] temp;
int readLen = 0;
int tmpoffset = 0;
while ((readLen = byteArrayStream.read(cbuf)) > 0) {
tmpoffset += readLen;
temp = fileByte;
fileByte = new byte[tmpoffset];
System.arraycopy(temp, 0, fileByte, 0, temp.length);
System.arraycopy(cbuf, 0, fileByte, temp.length, readLen);
}
byte decryptedData[] = cipher.doFinal(fileByte);
byteArrayStream.close();
outStream.write(decryptedData);
outStream.close();
}
public static byte[] subarray(byte[] dataByte, int start, int end) {
byte[] doData = new byte[end - start];
System.out.println(end - start);
int j = 0;
for (int i = start; i < end; i++) {
doData[j] = dataByte[i];
j++;
}
return doData;
}
}