You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SubtleCrypto加密无法被RSACryptoServiceProvider OAEP解密问题求助

RSA-OAEP加密对接问题:SubtleCrypto加密结果无法被RSACryptoServiceProvider解密

我跟这个问题死磕好一阵了,一直没搞定。服务端用的是RSACryptoServiceProvider做RSA-OAEP解密,而且这个实现完全没法修改,代码如下:

public void SetEncryptedPassword(string password) { 
    using (RSACryptoServiceProvider decrypter = new RSACryptoServiceProvider()) { 
        decrypter.FromXmlString(Resources.PrivateKey); 
        var decryptedBytes = decrypter.Decrypt(Convert.FromBase64String(password), true); 
        _password = Encoding.UTF8.GetString(decryptedBytes).ToSecureString(); 
    } 
}

我现在要实现一个Web客户端对接这个服务,但加密逻辑怎么调都不对。试了好几个库之后,只有SubtleCrypto能正常导入服务端提供的公钥(需要给公钥添加kty、alg、ext属性,还要转成URL Base64),加密能得到结果,但服务端解密就一直报错:Error occurred while decoding OAEP padding.。另外我发现自己加密出来的结果比iPad端和.NET服务生成的输出略短一点,不确定是不是这个差异导致的问题。我的加密代码如下:

const encrypt = async (msg)=>{ 
    let msgBytes = stringToBytes(msg); 
    let publicKey2 = await window.crypto.subtle.importKey("jwk",publicKey, {name:"RSA-OAEP", hash:"SHA-256"}, true, ["encrypt"]).catch((issue)=>console.log(issue)); 
    var result = await window.crypto.subtle.encrypt({name: "RSA-OAEP"}, publicKey2, msgBytes ); 
    var toBase64 = _arrayBufferToBase64(result); 
    return toBase64; 
}
_arrayBufferToBase64( buffer ) { 
    var binary = ''; 
    var bytes = new Uint8Array( buffer ); 
    var len = bytes.byteLength; 
    for (var i = 0; i < len; i++) { 
        binary += String.fromCharCode( bytes[ i ] ); 
    } 
    return window.btoa( binary ); 
}

希望能得到各位的排查建议,我可以随时补充需要的信息。

内容的提问来源于stack exchange,提问作者GreysonTyrus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:26:19