登录 Javascript 并在 Flask 中验证

问题描述

使用现有库在 Javascript 中签名和验证很容易。然而,如果我们想在 Javascript 中生成一个公私密钥对,签署一个文本然后在 Flask 中验证,这是令人困惑的。我已经知道了一些差异,比如 Javascript 端的认散列与 python 端的不同。但是Flask端的验证还是失败。

index.html

function send(){
    promise =   window.crypto.subtle.generateKey(algo,true,//whether the key is extractable (i.e. can be used in exportKey)
                    ["sign","verify"] //can be any combination of "sign" and "verify"
                    );
    console.log(promise)
    promise.then( (keys) => {
        priv = keys.privateKey
        pub = keys.publicKey
        console.log(pub)
        console.log(exportCryptoKey(pub))
        const pub_key_export = exportCryptoKey(pub)
        return pub_key_export.then( (pub_key) => {
            console.log("storing keys in",pub_key)
            signature = window.crypto.subtle.sign(algo,priv,enc_msg);
            signature.then((sign) => {
                sgn = window.btoa(ab2str(sign));
                $.post("verify",{"pub": pub_key,"data": ab2str(enc_msg),"signature": sgn},function(data){
                    console.log("data",data);
                })
            })
        })
    })
}

verify.py

def verifySignature(signature,data,pub_key):
    key = RSA.importKey(pub_key)
    h = SHA256.new(data.encode("utf-8"))
    verifier = PKCS1_v1_5.new(key)
    return verifier.verify(h,signature)

解决方法

btoa(raw_binary_bytes) 会将您的有效负载编码为 js 中的 base64,这样做是为了防止传输原始字节时出现问题。

您需要使用 base64.b64decode(encoded_bytes) 在 python 中调用 decode 方法以获取实际的加密字节,然后您可以解密