获取错误“无效的DES密钥大小。在用python加密消息时,密钥必须正好是8字节长

2024-10-06 12:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的java代码用一个pass key来编码一个字符串

     public static String encrypt(String message, String passkey) throws Exception {
     final MessageDigest md = MessageDigest.getInstance("SHA-1");
     final byte[] digestOfPassword = md.digest(passkey.getBytes("utf-8"));
     final byte[] keyBytes = ( byte[])resizeArray(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);

     String encryptedString = Base64.encodeBase64String(cipherText);         
     return encryptedString;
 }

现在,我将相同的代码转换成python(python2.7),并尝试如下所示。在

^{pr2}$

在des=皮德斯.des获取密钥大小无效。密钥的长度必须正好为8字节。“

我作为参数发送的密钥是“f!16*hw$sda66“ 有人能告诉我线路是否有问题吗 des=皮德斯.des(图例24)


Tags: key代码messagenewstring密钥bytemd
1条回答
网友
1楼 · 发布于 2024-10-06 12:41:32

我想你得到这个错误的原因是因为类初始化方法希望键正好是8,如果它是其他任何东西,它会引起你看到的错误,这是你从pyDes调用的类的init

# Initialisation
def __init__(self, key, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL):
    # Sanity checking of arguments.
    if len(key) != 8:
        raise ValueError("Invalid DES key size. Key must be exactly 8 bytes long.")

如果您这样做是为了调试:

^{pr2}$

我认为24岁的关键是不被接受。在

我可能错了,但一眼就知道了。在

相关问题 更多 >