import
javax.crypto.Cipher;
import
javax.crypto.spec.SecretKeySpec;
import
org.apache.commons.codec.binary.Base64;
/**
*
* @author Administrator
*
*/
public
class
AES {
public
static
String Encrypt(String sSrc, String sKey)
throws
Exception {
if
(sKey ==
null
) {
System.out.print(
"Key为空null"
);
return
null
;
}
if
(sKey.length() !=
16
) {
System.out.print(
"Key长度不是16位"
);
return
null
;
}
byte
[] raw = sKey.getBytes(
"utf-8"
);
SecretKeySpec skeySpec =
new
SecretKeySpec(raw,
"AES"
);
Cipher cipher = Cipher.getInstance(
"AES/ECB/PKCS5Padding"
);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte
[] encrypted = cipher.doFinal(sSrc.getBytes(
"utf-8"
));
return
new
Base64().encodeToString(encrypted);
}
public
static
String Decrypt(String sSrc, String sKey)
throws
Exception {
try
{
if
(sKey ==
null
) {
System.out.print(
"Key为空null"
);
return
null
;
}
if
(sKey.length() !=
16
) {
System.out.print(
"Key长度不是16位"
);
return
null
;
}
byte
[] raw = sKey.getBytes(
"utf-8"
);
SecretKeySpec skeySpec =
new
SecretKeySpec(raw,
"AES"
);
Cipher cipher = Cipher.getInstance(
"AES/ECB/PKCS5Padding"
);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte
[] encrypted1 =
new
Base64().decode(sSrc);
try
{
byte
[] original = cipher.doFinal(encrypted1);
String originalString =
new
String(original,
"utf-8"
);
return
originalString;
}
catch
(Exception e) {
System.out.println(e.toString());
return
null
;
}
}
catch
(Exception ex) {
System.out.println(ex.toString());
return
null
;
}
}
public
static
void
main(String[] args)
throws
Exception {
String cKey =
"1234567890123456"
;
String cSrc =
"www.gowhere.so"
;
System.out.println(cSrc);
String enString = AES.Encrypt(cSrc, cKey);
System.out.println(
"加密后的字串是:"
+ enString);
String DeString = AES.Decrypt(enString, cKey);
System.out.println(
"解密后的字串是:"
+ DeString);
}
}
return
new
Base64().encodeToString(encrypted);
我这边怎么没有encodeToString 这个方法? 只有encode()
想问下你用的org是多少版本的?
引用来自“zhonghua.zhi”的评论
return
new
Base64().encodeToString(encrypted);
我这边怎么没有encodeToString 这个方法? 只有encode()
想问下你用的org是多少版本的?
引用来自“何情”的评论
引用来自“纯天然原味酱”的评论
引用来自“小文大哥哥”的评论
引用来自“纯天然原味酱”的评论
這篇文章說明 PKCS5和PKCS7是可以互解的
另外回二樓的大大,較新的JAVA版本把Base64的方法改成靜態方法,可能會寫成
Base64.encodeToString(encrypted, 0);