BÀI 83 - MÃ HÓA CHUỖI STRING TRONG ANDROID

  • Link tham khảo: here

  • Code mã hóa

@SuppressLint("NewApi")

public static String MaHoaEncrypt(String strToEncrypt, String myKey) {

try {

MessageDigest sha = MessageDigest.getInstance("SHA-1");

byte[] key = myKey.getBytes(StandardCharsets.UTF_8);

key = sha.digest(key);

key = Arrays.copyOf(key, 16);

SecretKeySpec secretKey = new SecretKeySpec(key, "AES");

@SuppressLint("GetInstance")

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));

} catch (Exception e) {

System.out.println(e.toString());

}

return null;

}

  • Code giải mã

@SuppressLint("NewApi")

public static String GiaiMaDecrypt(String strToDecrypt, String myKey) {

try {

MessageDigest sha = MessageDigest.getInstance("SHA-1");

byte[] key = myKey.getBytes(StandardCharsets.UTF_8);

key = sha.digest(key);

key = Arrays.copyOf(key, 16);

SecretKeySpec secretKey = new SecretKeySpec(key, "AES");

@SuppressLint("GetInstance")

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");

cipher.init(Cipher.DECRYPT_MODE, secretKey);

return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));

} catch (Exception e) {

System.out.println(e.toString());

}

return null;

}