加密

Base64

jdk 1.8 以上可以直接使用 Base64 1.7以下要自製 或 找套件來用

SHA256

Mac sha256 = Mac.getInstance("HmacSHA256"); sha256.init(new SecretKeySpec(key.getBytes("UTF8"), "HmacSHA256")); byte[] a = sha256.doFinal(value.getBytes("UTF8"));

AES

參考資料:(https://www.itread01.com/content/1549524994.htmlarrow-up-right)

參考資料:(https://www.jianshu.com/p/b277b75013e4arrow-up-right)

加密

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

---

private final String cKey = "DyCgD3HGbZWxqAo4";

public static String Encrypt(String sSrc, String sKey) throws Exception {
    if (sKey == null) {
        System.out.print("Key為空null");
        return null;
    }
    // 判斷Key是否為16位
    if (sKey.length() != 16) {
        System.out.print("Key長度不是16位");
        return null;
    }
    byte[] raw = sKey.getBytes("utf-8");
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"演算法/模式/補碼方式"
    IvParameterSpec iv = new IvParameterSpec(cKey.getBytes());//使用CBC模式,需要一個向量iv,可增加加密演算法的強度
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
    byte[] encrypted = cipher.doFinal(sSrc.getBytes());
    return Base64.getEncoder().encodeToString(encrypted);//此處使用BASE64做轉碼功能,同時能起到2次加密的作用。
}

解密

Last updated