android aes加解密、md5加密


import android.util.Base64;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

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

public class AesUtils {

    private static final String AES_CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";
    private static final String AES = "AES";

    public static String encrypt(String strKey, String strClearText, String strIvParameter) {
        try {
            byte[] raw = strKey.getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, AES);
            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(strIvParameter.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] cipherText = cipher.doFinal(strClearText.getBytes());
            String strBase64Content = Base64.encodeToString(cipherText, Base64.DEFAULT);
            strBase64Content = strBase64Content.replaceAll(Objects.requireNonNull(System.getProperty("line.separator")), "");
            return strBase64Content;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String strKey, String strCipherText, String strIvParameter) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(strKey.getBytes(StandardCharsets.US_ASCII), AES);
            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(strIvParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] cipherText = Base64.decode(strCipherText, Base64.DEFAULT); // decode by BASE64 first
            byte[] clearText = cipher.doFinal(cipherText);
            return new String(clearText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

md5加密

public static String toMd5(String content) {
    byte[] hash;
    try {
        hash = MessageDigest.getInstance("MD5").digest(content.getBytes());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("NoSuchAlgorithmException", e);
    }
    StringBuilder hex = new StringBuilder(hash.length * 2);
    for (byte b : hash) {
        if ((b & 0xFF) < 0x10) {
            hex.append(0);
        }
        hex.append(Integer.toHexString(b & 0xff));
    }
    return hex.toString();
}
posted @ 2021-12-09 10:49  用户72093285  阅读(449)  评论(0)    收藏  举报