android中常用的文本加密方式总结

来源:互联网 发布:淘宝买欧式家具靠谱吗 编辑:程序博客网 时间:2024/05/17 22:26

主要介绍几种主流的加密方式,简单的有SHA-1加密、MD5加密,复杂的有AES加密。前两者是HASH算法加密,后者是对称加密算法。

1、SHA-1加密算法

说明:该算法主要用于简单的文本加密,一般是一行文本

public static String Md5(String str) {if (str != null && !str.equals("")) {try {MessageDigest md5 = MessageDigest.getInstance("MD5");char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };byte[] md5Byte = md5.digest(str.getBytes("UTF8"));StringBuffer sb = new StringBuffer();for (int i = 0; i < md5Byte.length; i++) {sb.append(HEX[(int) (md5Byte[i] & 0xff) / 16]);sb.append(HEX[(int) (md5Byte[i] & 0xff) % 16]);}str = sb.toString();} catch (NoSuchAlgorithmException e) {} catch (Exception e) {}}return str;}

2、MD5加密算法

说明:一般用于简单的文本加密

private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };public static String StringToSHA1(String input){String result="";try {MessageDigest sha1Digest=MessageDigest.getInstance("SHA-1");sha1Digest.update(input.getBytes());  byte[] resultBytes= sha1Digest.digest();int length=resultBytes.length;StringBuilder buf = new StringBuilder(length * 2);// 把密文转换成十六进制的字符串形式for (int i = 0; i < length; i++) {          buf.append(HEX_DIGITS[(resultBytes[i] >> 4) & 0x0f]);buf.append(HEX_DIGITS[resultBytes[i] & 0x0f]);}result= buf.toString().toUpperCase();} catch (NoSuchAlgorithmException e) {result="";}return result;}

3、AES加密算法

说明:该算法可以用于大文本的加密      

public class Encryption {public String str_salt ;public byte[] bytes_salt ;private static Encryption encryption ;private Encryption(){}public synchronized static Encryption getInstance() {if (encryption == null) {encryption = new Encryption();}return encryption ;}/* * 生成随机数,可以当做动态的密钥 * 加密和解密的密钥必须一致,不然将不能解密 */public String generateSalt(){try {SecureRandom localSecureRandom = SecureRandom.getInstance("SHA1PRNG");bytes_salt = new byte[20];localSecureRandom.nextBytes(bytes_salt) ;str_salt = toHex(bytes_salt) ;return str_salt ;} catch (Exception e) {e.printStackTrace();}return null;}/* * 加密 */public String encrypt(String seed, String cleartext) { if(!("".equals(seed))&&!("".equals(cleartext))){byte[] rawKey;try {rawKey = getRawKey(seed.getBytes());byte[] result = encrypt(rawKey, cleartext.getBytes());    return toHex(result);    } catch (Exception e) {e.printStackTrace();} }return null;       }            /* * 解密 */    public String decrypt(String seed, String encrypted) {      if(!("".equals(seed))&&!("".equals(encrypted))){    byte[] rawKey;    try {    rawKey = getRawKey(seed.getBytes());    byte[] enc = toByte(encrypted);        byte[] result = decrypt(rawKey, enc);        return new String(result);        } catch (Exception e) {    e.printStackTrace();    }        }return null;    }           private static byte[] getRawKey(byte[] seed) throws Exception {            KeyGenerator kgen = KeyGenerator.getInstance("AES");            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");            sr.setSeed(seed);            kgen.init(128, sr);            SecretKey skey = kgen.generateKey();            byte[] raw = skey.getEncoded();            return raw;        }                   private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");            Cipher cipher = Cipher.getInstance("AES");            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);            byte[] encrypted = cipher.doFinal(clear);            return encrypted;        }           private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");            Cipher cipher = Cipher.getInstance("AES");            cipher.init(Cipher.DECRYPT_MODE, skeySpec);            byte[] decrypted = cipher.doFinal(encrypted);            return decrypted;        }           public static String toHex(String txt) {            return toHex(txt.getBytes());        }        public static String fromHex(String hex) {            return new String(toByte(hex));        }                public static byte[] toByte(String hexString) {            int len = hexString.length()/2;            byte[] result = new byte[len];            for (int i = 0; i < len; i++)                result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();            return result;        }           public static String toHex(byte[] buf) {            if (buf == null)                return "";            StringBuffer result = new StringBuffer(2*buf.length);            for (int i = 0; i < buf.length; i++) {                appendHex(result, buf[i]);            }            return result.toString();        }        private final static String HEX = "0123456789ABCDEF";        private static void appendHex(StringBuffer sb, byte b) {            sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));        }}


 

0 0
原创粉丝点击