簡體   English   中英

JavaScript導出RSA-OAEP公鑰

[英]JavaScript Exporting RSA-OAEP public key

我試圖通過使用此處描述的導出密鑰來訪問公共密鑰。 我有以下代碼:

 window.crypto.subtle.generateKey( { name: "RSA-OAEP", modulusLength: 2048, //can be 1024, 2048, or 4096 publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512" }, true, //whether the key is extractable (ie can be used in exportKey) ["encrypt", "decrypt"] //must be ["encrypt", "decrypt"] or ["wrapKey", "unwrapKey"] ) .then(function(key){ //returns a keypair object console.log(key); console.log(key.publicKey); console.log(key.privateKey); window.crypto.subtle.exportKey("spki",key.publicKey) .then(function(keydata){ //returns the exported key data console.log(keydata); document.getElementById("key").innerHTML = String(key.publicKey) }) .catch(function(err){ console.error(err); }); }) 

我想查看公共密鑰,例如,將HTML元素設置為[object CryptoKey],然后將其設置為HTML元素。 如何直接訪問公鑰?

謝謝

編輯:

 window.crypto.subtle.generateKey( { name: "RSA-OAEP", modulusLength: 2048, //can be 1024, 2048, or 4096 publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512" }, true, //whether the key is extractable (ie can be used in exportKey) ["encrypt", "decrypt"] //must be ["encrypt", "decrypt"] or ["wrapKey", "unwrapKey"] ) .then(function(key){ //returns a keypair object console.log(key); console.log(key.publicKey); console.log(key.privateKey); window.crypto.subtle.exportKey("spki",key.publicKey) .then(function(keydata){ //returns the exported key data console.log(keydata); var publicKeyB64 = ab2str(keydata); document.getElementById("key").innerHTML = publicKeyB64; }) .catch(function(err){ console.error(err); }); }) function ab2str( 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 ); } 

keydata是一個ArrayBuffer,其中包含以DER格式導出的公鑰。 由於DER是二進制的,因此需要將結果編碼為文本,例如使用base64

在字符串和ArrayBuffers之間轉換中選擇首選函數以從ArrayBuffer 轉換為字符串

var  publicKeyB64 = btoa(ab2str(keydata));
document.getElementById("key").innerHTML = publicKeyB64;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM