java 加密工具类

java 加密工具类

public class SecretUtils {

/*
    private static final String ALGORITHM = ConfigItem.SECRET_ALGORITHM.value();
    private static final String KEY = ConfigItem.SECRET_KEY.value();
    */
    private static final String ALGORITHM = "AES"; //加密算法
    private static final String KEY = "jiayeli.cn@*,!."; //密钥,长度限制16, 24, 32 位


    public static String encrypt(String input) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encrypted = cipher.doFinal(input.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static String decrypt(String input) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decodedBytes = Base64.getDecoder().decode(input);
        byte[] decrypted = cipher.doFinal(decodedBytes);
        return new String(decrypted);
    }
    
   @Test
    public void encryptTestCase() throws Exception {
    	String ciphertext = SecretUtils.encrypt("hello world!");
        System.out.println("密文:" + ciphertext);
        System.out.println("明文: " + SecretUtils.decrypt("ciphertext"));
    }

}

public class SecretUtils {
private static final String ALGORITHM = ConfigItem.SECRET_ALGORITHM.value();
private static final String KEY = ConfigItem.SECRET_KEY.value();
public static String encrypt(String input) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encrypted = cipher.doFinal(input.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String input) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decodedBytes = Base64.getDecoder().decode(input);
byte[] decrypted = cipher.doFinal(decodedBytes);
return new String(decrypted);
}

@Test
public void encryptTestCase() throws Exception {
String ciphertext = SecretUtils.encrypt(“hello world!”);
System.out.println(“密文:” + ciphertext);
System.out.println("明文: " + SecretUtils.decrypt(“ciphertext”));
}
}

你可能感兴趣的:(java,开发语言)