1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.util.Base64Utils;
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.MessageDigest;
@Slf4j public class EncryptUtil { private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; private static final String CODE = "utf-8";
@Setter @Getter public static String encryptKey;
public static String encrypt(String content) { return encrypt(content, encryptKey); }
public static String encrypt(String content, String key) { try { byte[] encrypted = encrypt2bytes(content, key); return Base64Utils.encodeToString(encrypted); } catch (Exception e) { log.error("failed to encrypt: {} of {}", content, e); return null; } }
public static byte[] encrypt2bytes(String content, String key) { try { byte[] raw = key.getBytes(CODE); SecretKeySpec secretKeySpec = new SecretKeySpec(raw, KEY_ALGORITHM); Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); return cipher.doFinal(content.getBytes(CODE)); } catch (Exception e) { log.error("failed to encrypt: {} of {}", content, e); return null; } }
public static String decrypt(String content) { try { return decrypt(content, encryptKey); } catch (Exception e) { log.error("failed to decrypt: {}, e: {}", content, e); return null; } }
public static String decrypt(String content, String key) throws Exception { return decrypt(Base64Utils.decodeFromString(content), key); }
public static String decrypt(byte[] content, String key) throws Exception { if (key == null) { log.error("AES key should not be null"); return null; }
byte[] raw = key.getBytes(CODE); SecretKeySpec keySpec = new SecretKeySpec(raw, KEY_ALGORITHM); Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, keySpec); try { byte[] original = cipher.doFinal(content); return new String(original, CqODE); } catch (Exception e) { log.error("failed to decrypt content: {}/ key: {}, e: {}", content, key, e); return null; } } }
|