private static char[] encrypt(String pass) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, AES_KEY);
return Base64.encodeBase64String(cipher.doFinal(pass.getBytes())).toCharArray();
}
我如何在python中解密此密码?没有CBC模式,我找不到任何方法
答案 0 :(得分:0)
如果省略了模式和填充,则SunJCE提供程序将使用AES/ECB/PKCS5Padding
(https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#ciphertrans)
在https://gist.github.com/forkd/7ed4a8392fe7b69307155ab379846019上有一个使用该特性的Python示例 可以轻松修改:
from base64 import b64decode
from base64 import b64encode
from Crypto.Cipher import AES
# Padding
BLOCK_SIZE = 16 # Bytes
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
class AESCipher:
"""
Usage:
c = AESCipher('key').encrypt('message')
m = AESCipher('key').decrypt(c)
Tested under Python 3
"""
def __init__(self, key):
self.key = key.encode('utf8')
def encrypt(self, raw):
raw = pad(raw)
cipher = AES.new(self.key, AES.MODE_ECB)
return b64encode(cipher.encrypt(raw))
def decrypt(self, enc):
enc = b64decode(enc)
cipher = AES.new(self.key, AES.MODE_ECB)
return unpad(cipher.decrypt(enc)).decode('utf8')
## MAIN
# Test...
msg = 'This is a plain text...'
key = '12345678901234567890123456789012'
encrypt = AESCipher(key).encrypt(msg)
decrypt = AESCipher(key).decrypt(encrypt)
decryptFromJava = AESCipher(key).decrypt('hL1oPPxKbt2unCPyAWlZsWZO3HH/lg8DJ6eLdpYZjnxFBb85OLUxaM/G7ZXUHI0JOiBVpFd6UFcwJ5Ut65i3/rJf+DFz+T8wH/Og+9cz/ebOmvHirTfB1emsIyyKRZvx')
print('Ciphertext:', encrypt)
print('Decryted text:', decrypt)
print('Decryted text from Java:', decryptFromJava)
输出为:
Ciphertext: b'hL1oPPxKbt2unCPyAWlZsSXmQCzpJcEl1LPNmzVuL0o='
Decryted text: This is a plain text...
Decryted text from Java: This is a plain text encrypted with the Java encrypt-method which needs to be encypted...
而
hL1oPPxKbt2unCPyAWlZsWZO3HH/lg8DJ6eLdpYZjnxFBb85OLUxaM/G7ZXUHI0JOiBVpFd6UFcwJ5Ut65i3/rJf+DFz+T8wH/Og+9cz/ebOmvHirTfB1emsIyyKRZvx
是文本This is a plain text encrypted with the Java encrypt-method which needs to be encypted...
的Java加密方法的加密输出。
(使用32字节密钥:12345678901234567890123456789012
)
值得庆幸的是,
也可以通过例如https://tio.run/#python3。