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
时间: 2024-10-10 14:38:46