我有一个工作的java代码,它用3DES加密加密密码短语-
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Main{
public static void main(String[] args) throws Exception {
String text = "aug@2019";
String codedtext = new Main().encrypt(text);
System.out.println(codedtext);
}
public String encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("Lgp!kdao2020"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
final String encodedCipherText = new String(java.util.Base64.getMimeEncoder().encode(cipherText),
"UTF-8");
return encodedCipherText;
}
}
我希望在Python中使用相同的加密,因此从这两个代码生成的加密是相同的,这是我的Python代码
import base64
from Crypto.Cipher import AES
import pyDes
from Crypto import Random
import hashlib
def encrypt(message, passkey):
hash_object = hashlib.md5(passkey.encode("utf-8"))
digested_passkey = hash_object.digest()
print(digested_passkey)
key24 = digested_passkey[:24]
des = pyDes.des(key24);
message = message.encode('utf-8')
message = message + (16 - len(message) % 16) * chr(16 - len(message) % 16)
iv = Random.new().read(AES.block_size)
cipher = AES.new(des, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(message))
print(encrypt('aug@2019', 'Lgp!kdao2020'))
我收到一个错误->;ValueError:DES密钥大小无效。密钥的长度必须正好为8字节
两种代码之间有很多不同之处:
{: <24}
更改为[:24]
并不能使它变得更好)。最后的第二个更改digested_passkey[:24]
与digested_passkey
相同,并且有效,因为PyCryptodome根据2密钥三重DES自动将密钥扩展到24字节李>除此之外,所使用的算法是不安全的(MD5)或过时/缓慢的(三重DES),如评论中所述。同样,0-向量作为IV是完全不安全的
它以Java代码(
7B0aNUwOU1ECqKqnIZs6mQ==
)的形式给出结果相关问题 更多 >
编程相关推荐