1.通过AES算法对文本进行加密解密
package com.example.day43.jiami; import android.util.Log; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; 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.IvParameterSpec; /** * 通过AES算法对文本进行加密解密 */ public class AesUtils { public static final byte[] vaule = new byte[] { 92, 96, 21, 46, -92, -96, -21, -46, 92, 96, 21, 46 }; private static byte[] iv = new byte[] { // 算法参数 -12, 35, -25, 65, 45, -87, 95, -22, -15, 45, 55, -66, 32, 5 - 4, 84, 55 }; private static SecretKey key; // 加密密钥 private static AlgorithmParameterSpec paramSpec; // 算法参数 private static Cipher ecipher; // 加密算法 private final static int JELLY_BEAN_4_2 = 17; private static SecureRandom sr; static { KeyGenerator kgen; try { // 为指定算法生成一个密钥生成器对象。 kgen = KeyGenerator.getInstance("AES"); // 使用用户提供的随机源初始化此密钥生成器,使其具有确定的密钥长度。 if (android.os.Build.VERSION.SDK_INT >= JELLY_BEAN_4_2) { sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); } else { sr = SecureRandom.getInstance("SHA1PRNG"); } sr.setSeed(vaule); Log.i("sr", "rand.getProvider(): " + sr.getProvider().getName()); kgen.init(128, sr); // 使用KeyGenerator生成(对称)密钥。 key = kgen.generateKey(); // 使用iv中的字节作为IV来构造一个 算法参数。 paramSpec = new IvParameterSpec(iv); // 生成一个实现指定转换的 Cipher 对象 ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } } /** * 加密,使用指定数据源生成密钥,使用用户数据作为算法参数进行AES加密 * * @param msg * 加密的数据 * @return */ public static String encrypt(String msg) { String str = ""; if (msg != null) { try { // 用密钥和一组算法参数初始化此 cipher ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); // 加密并转换成16进制字符串 str = asHex(ecipher.doFinal(msg.getBytes())); } catch (BadPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } } return str; } /** * 解密,对生成的16进制的字符串进行解密 * * @param value * * @return */ public static String decrypt(String value) { if (value != null && !"".equals(value) && !"null".equals(value)) { try { ecipher.init(Cipher.DECRYPT_MODE, key, paramSpec); return new String(ecipher.doFinal(asBin(value))); } catch (BadPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } } return ""; } /** * 将字节数组转换成16进制字符串 * * @param buf * @return */ private static String asHex(byte buf[]) { StringBuffer strbuf = new StringBuffer(buf.length * 2); int i; for (i = 0; i < buf.length; i++) { if (((int) buf[i] & 0xff) < 0x10)// 小于十前面补零 strbuf.append("0"); strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); } return strbuf.toString(); } /** * 将16进制字符串转换成字节数组 * * @param src * @return */ private static byte[] asBin(String src) { if (src.length() < 1) return null; byte[] encrypted = new byte[src.length() / 2]; for (int i = 0; i < src.length() / 2; i++) { int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);// 取高位字节 int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);// 取低位字节 encrypted[i] = (byte) (high * 16 + low); } return encrypted; } }
2.通过Base64 算法对文本进行加密解密
package com.example.day43.jiami; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; public class Base64Utils { private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); /** * data[]进行编码 * * @param data * @return */ public static String encode(byte[] data) { int start = 0; int len = data.length; StringBuffer buf = new StringBuffer(data.length * 3 / 2); int end = len - 3; int i = start; int n = 0; while (i <= end) { int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 0x0ff) << 8) | (((int) data[i + 2]) & 0x0ff); buf.append(legalChars[(d >> 18) & 63]); buf.append(legalChars[(d >> 12) & 63]); buf.append(legalChars[(d >> 6) & 63]); buf.append(legalChars[d & 63]); i += 3; if (n++ >= 14) { n = 0; buf.append(" "); } } if (i == start + len - 2) { int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 255) << 8); buf.append(legalChars[(d >> 18) & 63]); buf.append(legalChars[(d >> 12) & 63]); buf.append(legalChars[(d >> 6) & 63]); buf.append("="); } else if (i == start + len - 1) { int d = (((int) data[i]) & 0x0ff) << 16; buf.append(legalChars[(d >> 18) & 63]); buf.append(legalChars[(d >> 12) & 63]); buf.append("=="); } return buf.toString(); } //解密 private static int decode(char c) { if (c >= 'A' && c <= 'Z') return ((int) c) - 65; else if (c >= 'a' && c <= 'z') return ((int) c) - 97 + 26; else if (c >= '0' && c <= '9') return ((int) c) - 48 + 26 + 26; else switch (c) { case '+': return 62; case '/': return 63; case '=': return 0; default: throw new RuntimeException("unexpected code: " + c); } } /** * Decodes the given Base64 encoded String to a new byte array. The byte * array holding the decoded data is returned. */ public static byte[] decode(String s) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { decode(s, bos); } catch (IOException e) { throw new RuntimeException(); } byte[] decodedBytes = bos.toByteArray(); try { bos.close(); bos = null; } catch (IOException ex) { System.err.println("Error while decoding BASE64: " + ex.toString()); } return decodedBytes; } private static void decode(String s, OutputStream os) throws IOException { int i = 0; int len = s.length(); while (true) { while (i < len && s.charAt(i) <= ' ') i++; if (i == len) break; int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + (decode(s.charAt(i + 3))); os.write((tri >> 16) & 255); if (s.charAt(i + 2) == '=') break; os.write((tri >> 8) & 255); if (s.charAt(i + 3) == '=') break; os.write(tri & 255); i += 4; } } }
3.通过MD5算法对文本进行加密解密
package example.yiyaoba.utils; import android.text.TextUtils; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Md5Utils { public static final String encodeBy32BitMD5(String source) { return encrypt(source, false); } private static final String encrypt(String source, boolean is16bit) { if (TextUtils.isEmpty(source)) { return null; } String encryptedStr = null; try { MessageDigest digester = MessageDigest.getInstance("MD5"); encryptedStr = convertToHexString(digester.digest(source .getBytes("utf-8"))); if (is16bit) { encryptedStr = encryptedStr.substring(8, 24); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encryptedStr; } private static final String convertToHexString(byte data[]) { int i; StringBuffer buf = new StringBuffer(); for (int offset = 0; offset < data.length; offset++) { i = data[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } return buf.toString(); } }