Android基礎之加密解密

MD5工具類(MD5是編碼方式):

public class MD5Utils {
    /**
     * 默認的密碼字符串組合,用來將字節轉換成 16 進製表示的字符,apache校驗下載的文件的正確性用的就是默認的這個組合
     */
    protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};//可改自己定義的

    /**
     * 生成字符串的md5校驗值
     *
     * @param s
     * @return
     */
    public static String MD5(String s) {
        return MD5(s.getBytes());
    }

    /**
     * 生成輸入流的md5校驗值,注意,<b>調用該方法後應該自己關閉輸入流</b>
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static String MD5(InputStream inputStream) {
        if (inputStream != null) {
            try {
                MessageDigest l_messagedigest = MessageDigest.getInstance("MD5");//獲取MD5的消息摘要實體
                byte[] buffer = new byte[1024];
                int numRead = 0;
                while ((numRead = inputStream.read(buffer)) > 0) {
                    l_messagedigest.update(buffer, 0, numRead);//往摘要信息裏添加數據
                }
                return bufferToHex(l_messagedigest.digest());//獲取摘要
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 生成文件的md5校驗值
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static String MD5(File file) {
        InputStream fis = null;
        try {
            fis = new FileInputStream(file);
            return MD5(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    public static String MD5(byte[] bytes) {
        try {
            MessageDigest l_messagedigest = MessageDigest.getInstance("MD5");
            l_messagedigest.update(bytes);
            return bufferToHex(l_messagedigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    private static String bufferToHex(byte bytes[]) {
        return bufferToHex(bytes, 0, bytes.length);
    }

    private static String bufferToHex(byte bytes[], int m, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);//一個字節八位 11111111對應FF FF爲兩個字符
        int k = m + n;//n爲length
        for (int l = m; l < k; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = hexDigits[(bt & 0xf0) >> 4]; // 取字節中高 4 位的數字轉換, >>>
        // 爲邏輯右移,將符號位一起右移,此處未發現兩種符號有何不同
        char c1 = hexDigits[bt & 0xf]; // 取字節中低 4 位的數字轉換
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }
}

AES加密:

public class AESUtils {

    private Cipher cipher;//加密類
    private SecretKeySpec key;//祕鑰類
    public static final String SEED_16_CHARACTER = "U1MjU1M0FDOUZ.Qz";//祕鑰  相互協商

    public AESUtils() {
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//加密算法,加密模式,填充方式
            key = new SecretKeySpec(SEED_16_CHARACTER.getBytes(), "AES");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String encrypt(String plainText) {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);//初始化加密類設置類型爲加密,祕鑰
            byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));//獲取明文的UTF-8編碼進行加密
            String encryptedText = new String(Base64.encode(encrypted,
                    Base64.DEFAULT), "UTF-8");//將密文字節轉成Base64編碼後再轉成UTF-8編碼(自行定義)並轉字節爲文本
            return encryptedText;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public String decrypt(String cryptedText) {
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);//解密模式  剩下的順序與加密相反
            byte[] bytes = Base64.decode(cryptedText, Base64.DEFAULT);
            byte[] decrypted = cipher.doFinal(bytes);
            String decryptedText = new String(decrypted, "UTF-8");
            return decryptedText;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

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