import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Base64;
/**
* @author binfirechen
* @version 1.0
* @date 2022/8/10 10:44
*/
public class EncryptTest {
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
private String AESEncrypt(String source,String encrypKey) throws Exception{
byte[] sourceByptes=source.getBytes("utf-8");
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encrypKey.getBytes(), "AES"));
byte[] bytes = cipher.doFinal(sourceByptes);
return Base64.getEncoder().encodeToString(bytes);
}
private String AESDecrypt(String source,String deencrypKey) throws Exception{
byte[] bytes = decryptByBytes(Base64.getDecoder().decode(source), deencrypKey);
return new String(bytes,"utf-8");
}
private byte[] decryptByBytes(byte[] encryptBytes, String deencrypKey) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(deencrypKey.getBytes(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return decryptBytes;
}
public static String getSHA256Str(String str) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
return Hex.encodeHexString(hash);
}
public static String encrypt(String content) throws UnsupportedEncodingException {
String value = DigestUtils.md5Hex(content.getBytes("UTF-8"));
return value.toUpperCase();
}
}