groovy实现AES加解密

文章目录
  1. 不推荐使用的 DES 加密
  2. 如何使用 groovy 实现 AES 加解密

主题:

  • 如何使用 groovy 实现 DES 加解密
  • 如何使用 groovy 实现 AES 加解密

不推荐使用的 DES 加密

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
import java.security.*
import javax.crypto.*
import javax.crypto.spec.*

//不安全,不推荐使用了
class DESCodec {
static encode = { String target ->
def cipher = getCipher(Cipher.ENCRYPT_MODE)
return cipher.doFinal(target.bytes).encodeBase64()
}

static decode = { String target ->
def cipher = getCipher(Cipher.DECRYPT_MODE)
return new String(cipher.doFinal(target.decodeBase64()))
}

private static getCipher(mode) {
def keySpec = new DESKeySpec(getPassword())
def cipher = Cipher.getInstance("DES")
def keyFactory = SecretKeyFactory.getInstance("DES")
cipher.init(mode, keyFactory.generateSecret(keySpec))
return cipher
}
private static getPassword() { "password".getBytes("UTF-8") }
}
//具体使用案例
def encode=DESCodec.encode(this.args[0])
def decode=DESCodec.decode(encode.toString())
println encode
println decode

如何使用 groovy 实现 AES 加解密

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
import org.apache.commons.codec.binary.Base64;
//满足公司安全要求的 AES 加密算法
class AESCodec {
public static String encrypt(String key, String initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: "+ Base64.encodeBase64String(encrypted));
return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

public static String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
//具体使用案例
def key = "Bar12345Bar12345" // 128 bit key
def initVector = "RandomInitVector" // 16 bytes IV
def account=AESCodec.decrypt(key,initVector,properties.account)
def password=AESCodec.decrypt(key,initVector,properties.password)
println account
println password