我正在尝试使用 Web Crypto API 的 SubtleCrypto 接口验证 JWT 的签名。
我的代码不会验证令牌签名,而 JWT.io 上的调试工具会,我不知道为什么。这是我的验证功能:
function verify (jwToken, jwKey) {
const partialToken = jwToken.split('.').slice(0, 2).join('.')
const signaturePart = jwToken.split('.')[2]
const encoder = new TextEncoder()
return window.crypto.subtle
.importKey('jwk', jwKey, {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' }
}, false, ['verify'])
.then(publicKey =>
window.crypto.subtle.verify(
{ name: 'RSASSA-PKCS1-v1_5' },
publicKey,
encoder.encode(atob(signaturePart)),
encoder.encode(partialToken)
).then(isValid => alert(isValid ? 'Valid token' : 'Invalid token'))
)
}
Run Code Online (Sandbox Code Playgroud)
我希望该代码能够工作并提供对正确签名的 JWT 的肯定验证。相反,示例代码无法验证签名令牌。这个例子在我的 Chrome 71 中失败了。
我还使用来自 RFC 7520 的示例数据设置了一些测试。
我正在存储我的数据,包括字符串格式的签名,在按照 MDN 文档将签名与字符串相互转换后,验证过程每次都会失败。相关的代码位是:
const publicKey: CryptoKey = await window.crypto.subtle.importKey("spki", str2ab(window.atob(publicKeyStr)), { name: "RSA-PSS", hash: { name: "SHA-256" } }, false, ["verify"]);
const privateKey: CryptoKey = await window.crypto.subtle.importKey("pkcs8", str2ab(window.atob(privateKeyStr)), { name: "RSA-PSS", hash: { name: "SHA-256" } }, false, ["sign"])
if(privateKey && publicKey) {
try {
const sign = await window.crypto.subtle.sign({name: "RSA-PSS", saltLength: 32}, privateKey, encodedMessage);
const signature = window.btoa(String.fromCharCode.apply(null, [...new Uint8Array(sign)])); //the way said signature is stored and I can load it
const res = await window.crypto.subtle.verify({name: "RSA-PSS", saltLength: 32}, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 SubtleCrypto 加密 javascript (firefox) 中的字符串。问题在于,加密仅适用于短输入。一旦字符串 (testdata) 超过 190 个字符,它将失败并出现操作错误。为什么 SubtleCrypto 会有这样的行为以及如何解决它?
代码:
function str2ab(str) {
var encoder = new TextEncoder('utf-8');
return encoder.encode(str);
}
function ab2str(buf) {
var decoder = new TextDecoder('utf-8');
return decoder.decode(buf);
}
var keypair;
var algorithmKeyGen = {
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([1,
0,
1
]), // Equivalent to 65537
hash: {
name: 'SHA-256'
}
};
var crypter = window.crypto.subtle;
function encrypt(buffer) {
return crypter.encrypt(algorithmKeyGen, keypair.publicKey, buffer).then(
function(data) {
alert(ab2str(data));
},
function(error) {
alert(error);
} …Run Code Online (Sandbox Code Playgroud) 我正在使用WebCrypto和RSASSA-PKCS1-v1_5(https://github.com/diafygi/webcrypto-examples#rsassa-pkcs1-v1_5---sign),我需要使用javascript代码将公钥导出为PEM格式.
文档说可以通过这种方式导出密钥:https: //github.com/diafygi/webcrypto-examples#rsassa-pkcs1-v1_5---exportkey 但我需要不同的格式.
任何的想法?
提前致谢.
问候
是否可以使用字符串作为加密密钥并仅使用 WebCryptoAPI 来加密 CryptoKey(私钥)?我实现了一个函数,但出现以下错误:
Uncaught (in promise) DOMException: AES key data must be 128 or 256 bits
Run Code Online (Sandbox Code Playgroud)
还有,我的功能。
function encryptPrivateKey() {
var promise = new Promise(function (resolve, reject) {
try {
var key = new TextEncoder().encode(pwd);
var iv = crypto.getRandomValues(new Uint8Array(12));
var alg = {name: 'AES-CTR', iv: iv};
window.crypto.subtle.importKey('raw', key, alg, false, ['encrypt']).then(function (key) {
window.crypto.subtle.encrypt(alg, key, privateKeyPEM).then(function (key) {
privateKey = key;
})
});
resolve(privateKey);
} catch (err) {
reject(Error(err));
}
});
return promise.then(function (result) {
return result;
}, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 WebCrypto 通过 RSA-PSS 对令牌进行签名,但我不断收到错误消息:
DataError: Data provided to an operation does not meet requirements
Run Code Online (Sandbox Code Playgroud)
在crypto.subtle.importKey。
这是我的 JavaScript 代码:
function signToken(token, key) {
crypto.subtle.importKey(
'pkcs8',
PEM2Binary(key),
{
name: 'RSA-PSS',
hash: { name: 'SHA-256' },
},
false,
['sign']
).then(function(privKey){
crypto.subtle.sign(
'RSA-PSS',
privKey,
new TextEncoder().encode(token)
).then(function(signedToken){
msg = JSON.stringify({ intent: 'authenticate-token', signedToken: signedToken });
socket.send(msg);
})
}).catch(function(error){
console.error(error);
})
}
function PEM2Binary(pem) {
var encoded = '';
var lines = pem.split('\n');
for (var i = 0; i < lines.length; i++) …Run Code Online (Sandbox Code Playgroud) 在服务器端,我使用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 …Run Code Online (Sandbox Code Playgroud)我正在尝试使用IE11的JavaScript通过以下代码实现公钥加密:
<script>
var data = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
var crypto = window.crypto || window.msCrypto;
var cryptoSubtle = crypto.subtle;
var genOp = cryptoSubtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: "SHA-256" },
},
true,
["encrypt", "decrypt"]
);
genOp.onerror = function (e) {
console.error(e);
};
genOp.oncomplete = function (e) {
var key = e.target.result;
console.log(key);
console.log(key.publicKey);
var encOp = cryptoSubtle.encrypt(
{
name: "RSA-OAEP"
},
key.publicKey,
data
);
encOp.onerror …Run Code Online (Sandbox Code Playgroud) encryption internet-explorer public-key-encryption internet-explorer-11 webcrypto-api
标题说明了一切.我想知道如何使用WebCrypto API生成RSA密钥对,如何使用密码保护它,以便将其存储在数据库中.
javascript cryptography passphrase webcrypto-api private-key
我已阅读此文档以通过ECDH-CURVE25519算法生成密钥对。但是当我在window.crypto.subtle.generateKey中指定ECDH-CURVE25519作为算法名称时,会抛出JS 错误(DOMException: Algorithm: Unrecognized name ) 。
window.crypto.subtle.generateKey(
{
name: "ECDH-CURVE25519"
},
true,
["deriveKey", "deriveBits"]
)
.then(function(key){
console.log(key);
pk = key.publicKey;
vk = key.privateKey;
})
.catch(function(err){
console.error(err);
});
Run Code Online (Sandbox Code Playgroud) webcrypto-api ×10
javascript ×8
rsa ×4
cryptography ×3
encryption ×3
private-key ×2
aes ×1
jwt ×1
node.js ×1
passphrase ×1
passwords ×1
pycryptodome ×1
signing ×1
subtlecrypto ×1
typescript ×1