在服务器端,我正在使用PyCryptodome通过RSA-OAEP(带有SHA-256)对消息进行加密。
我正在尝试使用客户端上的SubtleCrypto Web Crypto API解密消息,但是它给了我DOMException错误,没有更多详细信息。
在SubtleCrypto上,我可以毫无问题地导入PyCryptodome中生成的私钥,但是当我尝试解密消息时,它给了我错误。
我还尝试导入客户端PyCryptodome上生成的公钥,以使用SubtleCrypto加密相同的消息。在那种情况下,我可以使用与以前相同的流程对其进行解密,而不会出现问题。
这两个库之间的RSA-OAEP算法是否不兼容?我注意到PyCryptodome在各自的文档中引用了RFC 8017(v2.2)和SubtleCrypto RFC 3447(v2.1)。
编辑:
服务器端代码(pycryptodome == 3.9.8):
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
class Cipher:
def rsa_encrypt(self, data, key_string):
key = RSA.importKey(key_string)
rsa_encryption_cipher = PKCS1_OAEP.new(key)
ciphertext = rsa_encryption_cipher.encrypt(data)
return base64.b64encode(ciphertext)
def rsa_decrypt(self, data, key_string):
data = base64.b64decode(data)
key = RSA.importKey(key_string)
rsa_decryption_cipher = PKCS1_OAEP.new(key)
plaintext = rsa_decryption_cipher.decrypt(data)
return plaintext
( ... )
客户端代码
private decryptRSAString (encryptedText: string, privateKey: string) : Observable<ArrayBuffer> {
return Observable.create ((observer: any) => {
let keyBuffer: ArrayBuffer = this.str2ab(window.atob(privateKey));
let encryptedTextBuffer: ArrayBuffer = this.str2ab(window.atob(encryptedText));
let algorithmParams: RsaHashedImportParams = {
name: "RSA-OAEP",
hash: "SHA-256"
};
window.crypto.subtle.importKey(
'pkcs8',
keyBuffer,
algorithmParams,
true,
["decrypt"]
).then (
(cryptoKey: CryptoKey) => {
window.crypto.subtle.decrypt(
{
name: "RSA-OAEP"
},
cryptoKey,
encryptedTextBuffer
).then (
(decryptedMessage: ArrayBuffer) => {
observer.next (decryptedMessage);
observer.complete();
},
(error: any) => {
observer.error (error)
}
)
},
(error: any) => {
observer.error (error)
}
);
});
}
PyCryptodome并没有为默认消化了OAEP,但SHA-1,申请SHA-256在这里。因此,必须在WebCrypto端使用SHA-1 :
let algorithmParams: RsaHashedImportParams = {
name: "RSA-OAEP",
hash: "SHA-1"
};
当然,您也可以在PyCryptodome侧应用SHA-256 ,然后在WebCrypto侧无需更改。
from Crypto.Hash import SHA256
...
rsa_encryption_cipher = PKCS1_OAEP.new(key, SHA256) # default: Crypto.Hash.SHA1
通过双方一致的摘要,我可以使用您以前使用PyCryptodome代码(使用我自己的密钥)生成的WebCrypto代码成功解密密文。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句