python实现的AESECBPKCS5Padding和java相互解密和加密
AES(Advanced Encryption Standard) 是⼀种⾼级的对称加密的加密算法.
所以说他的加密和解密使⽤的是相同的key.
但是python 实现的AES加密算法是有点缺陷的,就是对加密的key 的长度有限制,长度必须是16,24,32 个字节,分别对应AES-128,
AES-192 or AES-256
所以说要和java 实现互通,就必须规定加密key的长度
代码如下:
import base64
from Crypto.Cipher import AES
SECRET_KEY ='0123456789ABCDEF'# 此处16|24|32个字符
class AES_ENCRYPT(object):
def__init__(self):
self.key = SECRET_KEY
def pading(self, text):
"""对加密字符的处理"""
return text +(len(self.key)-len(text)%len(self.key))*chr(len(self.key)-len(text)%len(self.key))
def unpading(self, text):
"""对解密字符的处理"""
return text[0:-ord(text[-1:])]
def getKey(self, key):
"""对key的处理,key 的长度 16,24,32"""
key_len =len(key)
if key_len <=16:
key +="0"*(16- key_len)
elif16< key_len <=24:
key +="0"*(24- key_len)
elif key_len <=32:
key +="0"*(32- key_len)
else:
key = key[:32]
return key
# 加密函数
def encrypt(self, text):
cryptor = w(de("utf-8"), de)# ECB 模式
self.ciphertext = pt(bytes(self.pading(text), encoding="utf8"))
encrypt_string =str(base64.b64encode(self.ciphertext)).lstrip("b")
return encrypt_string
# 解密函数
def decrypt(self, text):
decode = base64.b64decode(text)
cryptor = w(de("utf8"), de)# ECB 模式
plain_text = cryptor.decrypt(decode)
decrypt_string =str(self.unpading(plain_text)).lstrip("b")
return decrypt_string
if __name__ =='__main__':
aes_encrypt = AES_ENCRYPT()
en ="floutclouds@163"
print(pt(en))
print(aes_encrypt.decrypt('Qys1AGuyCEOYi/khjfSG3HGkevwhTeKgLXrbfg7yDaU='))
加密后的结果如图:
java 代码
package TWO.SUM;
import BASE64Decoder;
import BASE64Encoder;
import Cipher;
import SecretKeySpec;
public class TEST01 {
private static String sKey ="0123456789ABCDEF";
/
/ 加密
public static String encrypt(String sSrc)throws Exception {
Cipher cipher = Instance("AES/ECB/PKCS5Padding");
byte[] raw = Bytes();
SecretKeySpec skeySpec =new SecretKeySpec(raw,"AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.Bytes("utf-8"));
return new BASE64Encoder().encode(encrypted);//此处使⽤BASE64做转码。
}
// 解密
public static String decrypt(String sSrc){
try{
byte[] raw = Bytes();
SecretKeySpec skeySpec =new SecretKeySpec(raw,"AES");
Cipher cipher = Instance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 =new BASE64Decoder().decodeBuffer(sSrc);//先⽤base64解密
byte[] original = cipher.doFinal(encrypted1);
String originalString =new String(original,"utf-8");
return originalString;
}catch(Exception ex){
return null;
}
}
public static void main(String[] args){
String email ="floutclouds@163";
try{
System.out.println(decrypt("Qys1AGuyCEOYi/khjfSG3HGkevwhTeKgLXrbfg7yDaU=")); String sec =encrypt(email);
System.out.println(sec);
}catch(Exception e){
e.printStackTrace();
}
}
}
解密后的结果:python转java代码
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论