1

我使用以下内容在Javascript中加密

function encrypt(input, key){
    console.log("Input: " + input);  
    var secret_key = CryptoJS.SHA256(key);
    var iv = CryptoJS.lib.WordArray.random(16);
    console.log("IV: "+ iv);
    var body = CryptoJS.AES.encrypt(input, secret_key, {iv: iv,mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
    iv.concat(body.ciphertext);
    return toBase64String(iv);
}

这就是我在 Python/Django/Pycryptodome 中解密的方式:

def actsignin(request):
    global key
    global prime
    global base_num

    encrypted_string = request.GET['encrypted_string']

    print("Encrypted string decoded: ",base64.b64decode(encrypted_string).hex())
    print("----")
    encrypted = base64.b64decode(encrypted_string)
    IV = encrypted[:BLOCK_SIZE]
    print("IV: ",IV)
    sha256_key = SHA256.new(data=bytes(key))
    cipher = AES.new(sha256_key.digest(),AES.MODE_CBC)
    print(unpad(cipher.decrypt(encrypted[BLOCK_SIZE:]),BLOCK_SIZE))
    print('in signin')
    return render(request,"Shenzen/display.html",{'student':'student'})

它仍然说

Encrypted string decoded:  d9c9c21a9c2b5f46bc89933d82e1c1ef6c36dee1dc448b596d28bd3b5db45323
----
IV:  b'\xd9\xc9\xc2\x1a\x9c+_F\xbc\x89\x93=\x82\xe1\xc1\xef'
Internal Server Error: /Shenzen/actsignin/
Traceback (most recent call last):
  File "/home/tarunmaganti/Documents/AbhiramSlavery/ProjectLogin/hell/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/tarunmaganti/Documents/AbhiramSlavery/ProjectLogin/hell/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/tarunmaganti/Documents/AbhiramSlavery/ProjectLogin/hell/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/tarunmaganti/Documents/AbhiramSlavery/ProjectLogin/UrbanHell/Shenzen/views.py", line 82, in actsignin
    print(unpad(cipher.decrypt(encrypted[BLOCK_SIZE:]),BLOCK_SIZE))
  File "/home/tarunmaganti/Documents/AbhiramSlavery/ProjectLogin/hell/lib/python3.6/site-packages/Crypto/Util/Padding.py", line 90, in unpad
    raise ValueError("Padding is incorrect.")

BLOCK_SIZE 为 16,Key 是使用 DH 算法生成的。


问题:

填充似乎不正确。我似乎在两边都使用了 SHA256 作为密钥。
双方的 IV 输出似乎都是正确的。
所以,我在这两种情况下都在使用相同的字符串。因为,填充通常发生在输入字符串上,所以我已经解密并尝试在 Python 中取消填充,这表明填充不正确。


尝试以下评论: 1. IV 未在 python 代码中传递。
结果没有改变

  1. 你确定钥匙是一样的吗?分别在 JS 和 Python 中使用console.log(secret_key.toString())和。print("Sha256 of the key: ",sha256_key.digest())两者都不一样。为什么会这样?对于相同的输入,哈希不应该相同吗?
4

0 回答 0