Android DES AES MD5加密

AES加密:

<span style="font-size:18px;">package com.example.encrypdate.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AES {
	/**
	 * 加密
	 * 
	 * @param content
	 *            需要加密的內容
	 * @param password
	 *            加密密碼
	 * @return
	 */
	public static byte[] encrypt(String content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            待解密內容
	 * @param password
	 *            解密密鑰
	 * @return
	 */
	public static byte[] decrypt(byte[] content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 將十進制轉換成16進制
	 * 
	 * @param buf
	 * @return
	 */
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 將16進制轉換爲十進制
	 * 
	 * @param hexStr
	 * @return
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
					16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

}</span>
DES加密:

<span style="font-size:18px;">package com.example.encrypdate.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;

public class DES {
	// 初始化向量,隨機填充
	private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };

	/**
	 * @param encryptString
	 *            需要加密的明文
	 * @param encryptKey
	 *            祕鑰
	 * @return 加密後的密文
	 * @throws Exception
	 */
	public static String encryptDES(String encryptString, String encryptKey)
			throws Exception {
		// 實例化IvParameterSpec對象,使用指定的初始化向量
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		// 實例化SecretKeySpec類,根據字節數組來構造SecretKey
		SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
		// 創建密碼器
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		// 用祕鑰初始化Cipher對象
		cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
		// 執行加密操作
		byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

		return Base64.encodeToString(encryptedData, Base64.DEFAULT);
	}

	/****
	 * 
	 * @param decrypString
	 *            密文
	 * @param decryptKey
	 *            解密密鑰
	 * @return
	 * @throws Exception
	 */
	public static String decryptDES(String decrypString, String decryptKey)
			throws Exception {

		byte[] byteMi = Base64.decode(decrypString, Base64.DEFAULT);
		// 實例化IvParameterSpec對象,使用指定的初始化向量
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		// 實例化SecretKeySpec類,根據字節數組來構造SecretKey
		SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
		// 創建密碼器
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		// 用祕鑰初始化Cipher對象
		cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
		// 執行解密操作
		byte[] decryptedData = cipher.doFinal(byteMi);

		return new String(decryptedData);
	}
}</span>
MD5加密:

<span style="font-size:18px;">package com.example.encrypdate.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {

	/***
	 * @param data
	 * @return
	 */
	public static String toMD5(String data) {

		try {
			// 實例化一個指定摘要算法爲MD5的MessageDigest對象
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			// 重置摘要以供再次使用
			algorithm.reset();
			// 使用bytes更新摘要
			algorithm.update(data.getBytes());
			// 使用指定的byte數組對摘要進行最的更新,然後完成摘要計算
			return toHexString(algorithm.digest(), "");
		} catch (NoSuchAlgorithmException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
		return "";
	}

	// 將字符串中的每個字符轉換爲十六進制
	private static String toHexString(byte[] bytes, String separator) {

		StringBuilder hexstring = new StringBuilder();
		for (byte b : bytes) {
			String hex = Integer.toHexString(0xFF & b);
			if (hex.length() == 1) {
				hexstring.append('0');
			}
			hexstring.append(hex);

		}

		return hexstring.toString();
	}

}
</span>

測試文件:

<span style="font-size:18px;">package com.example.encrypdate;

import com.example.encrypdate.util.AES;
import com.example.encrypdate.util.DES;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import com.example.encrypdate.util.MD5;

public class MainActivity extends Activity {

	private TextView tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) this.findViewById(R.id.tv);
		// DESTest();
		// MD5Test();
		AESTest();
	}

	public void DESTest() {
		// 指定祕鑰 只能是8位
		String key = "12345678";
		// 指定需要加密的明文
		String text = "多少";
		Log.i("DES", "DES加密明文:" + text + "\n加密祕鑰:" + key);
		// 調用DES加密
		try {
			String encryptResult = DES.encryptDES(text, key);
			String decryptResult = DES.decryptDES(encryptResult, key);
			tv.setText("加密結果:" + encryptResult + "\n解密結果:" + decryptResult);
			Log.i("DES", "加密結果:" + encryptResult + "\n解密結果:" + decryptResult);
		} catch (Exception e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
	}

	private void AESTest() {
		String content = "test3444";
		String password = "11";
		// 加密
		byte[] encryptResult = AES.encrypt(content, password);
		String encryptResultStr = AES.parseByte2HexStr(encryptResult);
		// 解密
		byte[] decryptFrom = AES.parseHexStr2Byte(encryptResultStr);
		String decryptResult = new String(AES.decrypt(decryptFrom, password));

		Log.i("AES", "密碼:" + password + "\n加密前:" + content + "\n加密後:"
				+ encryptResultStr + "\n解密後:" + decryptResult);
		tv.setText("密碼:" + password + "\n加密前:" + content + "\n加密後:"
				+ encryptResultStr + "\n解密後:" + decryptResult);
	}

	private void MD5Test() {
		String str = "1nakjnvjanbdvjk女嘉賓那覅v驕傲不能浪費的哪裏方便v啊別v驕傲不能浪費的哪裏方便v啊別v驕傲不能浪費的哪裏方便v啊別浪費vu巴婁病v阿拉伯風v ";
		String MD5Result = MD5.toMD5(str);
		Log.i("MD5", str + "  MD5加密結果:" + MD5Result);
		tv.setText(str + "  MD5加密結果:" + MD5Result);
	}
}
</span>

完整工程地址:

http://download.csdn.net/detail/u014071669/7930951

另外,非對稱加密RSA詳解見:

http://blog.csdn.net/yongbingchao/article/details/39346099

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章