import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 採用MD5加密解密
* @author tfq
* @datetime 2011-10-13
*/
public class MD5Util {
/***
* MD5加碼 生成32位md5碼
*/
public static String string2MD5(String inStr){
MessageDigest md5 = null;
try{
md5 = MessageDigest.getInstance("MD5");
}catch (Exception e){
System.out.println(e.toString());
e.printStackTrace();
return "";
}
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++){
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 加密解密算法 執行一次加密,兩次解密
*/
public static String convertMD5(String inStr){
char[] a = inStr.toCharArray();
for (int i = 0; i < a.length; i++){
a[i] = (char) (a[i] ^ 't');
}
String s = new String(a);
return s;
}
// 測試主函數
public static void main(String args[]) {
String s = new String("tangfuqiang");
System.out.println("原始:" + s);
System.out.println("MD5後:" + string2MD5(s));
System.out.println("加密的:" + convertMD5(s));
System.out.println("解密的:" + convertMD5(convertMD5(s)));
}
}
2、異或加密
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
try {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("E:\\ico2.png"));
List<Integer> list =new ArrayList<Integer>();//定義集合<字節>用來存儲數據
int len; //定義變量,用來存儲數據
while((len=bis.read()) !=-1) //循環讀取,直到讀取到末尾爲止
list.add(len^123);
bis.close(); //關閉輸入流
BufferedOutputStream bos =new BufferedOutputStream(new FileOutputStream("E:\\ico2.png"));
for(Integer i:list)//遍歷集合,將所有數據寫回文件
bos.write(i);
bos.close(); //關閉輸出流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//從文件中逐個字節讀取數據,異或密碼,存入集合
}
}
3、cipher 加密
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import android.util.Log;
/**
* 使用AES對文件進行加密和解密
*
*/
public class CipherUtil {
/**
* 使用AES對文件進行加密和解密
*
*/
private static String type = "AES";
/**
* 把文件srcFile加密後存儲爲destFile
* @param srcFile 加密前的文件
* @param destFile 加密後的文件
* @param privateKey 密鑰
* @throws GeneralSecurityException
* @throws IOException
*/
public static void encrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {
Key key = getKey(privateKey);
Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(mkdirFiles(destFile));
crypt(fis, fos, cipher);
Log.i("tag", "in encrypt ----");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
}
}
/**
* 把文件srcFile解密後存儲爲destFile
* @param srcFile 解密前的文件
* @param destFile 解密後的文件
* @param privateKey 密鑰
* @throws GeneralSecurityException
* @throws IOException
*/
public static void decrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {
Key key = getKey(privateKey);
Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(mkdirFiles(destFile));
crypt(fis, fos, cipher);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
}
}
/**
* 根據filePath創建相應的目錄
* @param filePath 要創建的文件路經
* @return file 文件
* @throws IOException
*/
private static File mkdirFiles(String filePath) throws IOException {
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
return file;
}
/**
* 生成指定字符串的密鑰
* @param secret 要生成密鑰的字符串
* @return secretKey 生成後的密鑰
* @throws GeneralSecurityException
*/
private static Key getKey(String secret) throws GeneralSecurityException {
KeyGenerator kgen = KeyGenerator.getInstance(type);
kgen.init(128, new SecureRandom(secret.getBytes()));
SecretKey secretKey = kgen.generateKey();
return secretKey;
}
/**
* 加密解密流
* @param in 加密解密前的流
* @param out 加密解密後的流
* @param cipher 加密解密
* @throws IOException
* @throws GeneralSecurityException
*/
private static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, GeneralSecurityException {
int blockSize = cipher.getBlockSize() * 1000;
int outputSize = cipher.getOutputSize(blockSize);
byte[] inBytes = new byte[blockSize];
byte[] outBytes = new byte[outputSize];
int inLength = 0;
boolean more = true;
while (more) {
inLength = in.read(inBytes);
if (inLength == blockSize) {
int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
out.write(outBytes, 0, outLength);
} else {
more = false;
}
}
if (inLength > 0)
outBytes = cipher.doFinal(inBytes, 0, inLength);
else
outBytes = cipher.doFinal();
out.write(outBytes);
}
/**
* 刪除目錄及文件遞歸函數
* @param file
*/
public static void delDir(File file){
File[] files=file.listFiles();
for(File f:files){
while(f.exists())
if(f.isFile()){
f.delete();
}else {
if(f.delete())
System.out.println(f.getName()+"deleted");
else
delDir(f);
}
}
}
/**
* 刪除文件,可以是單個文件或文件夾
* @param fileName 待刪除的文件名
* @return 文件刪除成功返回true,否則返回false
*/
public static boolean delete(String fileName){
File file = new File(fileName);
if(!file.exists()){
System.out.println("刪除文件失敗:"+fileName+"文件不存在");
return false;
}else{
if(file.isFile()){
return deleteFile(fileName);
}else{
return deleteDirectory(fileName);
}
}
}
/**
* 刪除單個文件
* @param fileName 被刪除文件的文件名
* @return 單個文件刪除成功返回true,否則返回false
*/
public static boolean deleteFile(String fileName){
File file = new File(fileName);
if(file.isFile() && file.exists()){
file.delete();
return true;
}else{
return false;
}
}
/**
* 刪除目錄下的文件
* @param file
*/
/**
* 刪除目錄(文件夾)以及目錄下的文件
* @param dir 被刪除目錄的文件路徑
* @return 目錄刪除成功返回true,否則返回false
*/
public static boolean deleteDirectory(String dir){
//如果dir不以文件分隔符結尾,自動添加文件分隔符
if(!dir.endsWith(File.separator)){
dir = dir+File.separator;
}
File dirFile = new File(dir);
//如果dir對應的文件不存在,或者不是一個目錄,則退出
if(!dirFile.exists() || !dirFile.isDirectory()){
return false;
}
boolean flag = true;
//刪除文件夾下的所有文件(包括子目錄)
File[] files = dirFile.listFiles();
for(int i=0;i<files.length;i++){
//刪除子文件
if(files[i].isFile()){
flag = deleteFile(files[i].getAbsolutePath());
if(!flag){
break;
}
}
//刪除子目錄
else{
flag = deleteDirectory(files[i].getAbsolutePath());
if(!flag){
break;
}
}
}
if(!flag){
System.out.println("刪除目錄失敗");
return false;
}
//刪除當前目錄
if(dirFile.delete()){
return true;
}else{
System.out.println("刪除目錄"+dir+"失敗!");
return false;
}
}
/**
* 將文件夾的所有文件解密到另一個文件夾
* @param pathFile
* @throws IOException
* @throws GeneralSecurityException
*/
public static int decryptDir(String srcDir,String decryptDir)
throws GeneralSecurityException, IOException {
int num = 0;
File file = new File(srcDir);
if(file==null||!file.exists()){
file.mkdir();
}
if (file != null && file.exists()) {
File[] files = file.listFiles();
//遍歷當前目錄下的文件和文件夾(忽略點文件),存進ArrayList
for (File f : files) {
if(f.getName().endsWith(".dat")||f.getName().endsWith(".DAT")){
String fname = f.getName().replace(".dat", ".jpg");
fname = fname.replace(".DAT", ".jpg");
decrypt(f.getPath(), decryptDir+fname, CommonUtil.KEY_STR);
num++;
}
}
}
return num;
}
}