ECBUtil.java
2.74 KB
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
package com.yoho.unions.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* Created by zhengwen.ge on 2017/9/19.
*/
public class ECBUtil {
public static String SECRETKEY = "yoho9646abcdefgh";
public static final String KEY_ALGORITHM = "AES";
public static final String ECB_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
public static final String CBC_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
public static final String PLAIN_TEXT = "MANUTD is the greatest club in the world";
public static String encrypt(String key, String data)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException, IOException {
byte[] dataBytes = data.getBytes();
byte[] keyBytes = key.getBytes();
// 必须为 128bit或256bit,即 16字节或32字节
if (keyBytes.length != 16 && keyBytes.length != 32) {
return "";
}
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
SecretKeySpec k = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, k);
byte[] bytes = cipher.doFinal(dataBytes);
return Base64.encodeBase64String(cipher.doFinal(dataBytes));
}
public static String decrypt(String key, String data) {
data = data.replace(" ", "+");
// System.out.println("字串1是:" + data);
byte[] keyBytes = key.getBytes();
byte[] dataBytes = Base64.decodeBase64(data);
// 必须为 128bit或256bit,即 16字节或32字节
if (keyBytes.length != 16 && keyBytes.length != 32) {
return data;
}
try {
Cipher cipher = Cipher.getInstance("AES");//
SecretKeySpec k = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.DECRYPT_MODE, k);
return new String(cipher.doFinal(dataBytes)).trim();
} catch (Exception e) {
e.printStackTrace();
try{
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");//
SecretKeySpec k = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.DECRYPT_MODE, k);
return new String(cipher.doFinal(dataBytes)).trim();
}catch(Exception e1){
return data;
}
}
}
}