Buscar..


Observaciones

Las API de WebCrypto generalmente solo están disponibles en orígenes "seguros", lo que significa que el documento debe haberse cargado a través de HTTPS o desde la máquina local (desde localhost , file: o una extensión del navegador).

Estas API se especifican en la Recomendación del candidato de la API de criptografía web del W3C .

Datos criptográficamente aleatorios

// Create an array with a fixed size and type.
var array = new Uint8Array(5);

// Generate cryptographically random values
crypto.getRandomValues(array);

// Print the array to the console
console.log(array);

crypto.getRandomValues(array) se puede usar con instancias de las siguientes clases (descritas más adelante en Datos Binarios ) y generará valores de los rangos dados (ambos extremos inclusive):

  • Int8Array : -2 7 a 2 7 -1
  • Uint8Array : 0 a 2 8 -1
  • Int16Array : -2 15 a 2 15 -1
  • Uint16Array : 0 a 2 16 -1
  • Int32Array : -2 31 a 2 31 -1
  • Uint32Array : 0 a 2 31 -1

Creación de resúmenes (por ejemplo, SHA-256)

// Convert string to ArrayBuffer. This step is only necessary if you wish to hash a string, not if you aready got an ArrayBuffer such as an Uint8Array.
var input = new TextEncoder('utf-8').encode('Hello world!');

// Calculate the SHA-256 digest
crypto.subtle.digest('SHA-256', input)
// Wait for completion
.then(function(digest) {
  // digest is an ArrayBuffer. There are multiple ways to proceed.

  // If you want to display the digest as a hexadecimal string, this will work:
  var view = new DataView(digest);
  var hexstr = '';
  for(var i = 0; i < view.byteLength; i++) {
    var b = view.getUint8(i);
    hexstr += '0123456789abcdef'[(b & 0xf0) >> 4];
    hexstr += '0123456789abcdef'[(b & 0x0f)];
  }
  console.log(hexstr);

  // Otherwise, you can simply create an Uint8Array from the buffer:
  var digestAsArray = new Uint8Array(digest);
  console.log(digestAsArray);
})
// Catch errors
.catch(function(err) {
  console.error(err);
});

El borrador actual sugiere proporcionar al menos SHA-1 , SHA-256 , SHA-384 y SHA-512 , pero esto no es un requisito estricto y está sujeto a cambios. Sin embargo, la familia SHA todavía puede considerarse una buena opción ya que probablemente sea compatible con todos los navegadores principales.

Generando par de claves RSA y convirtiendo a formato PEM

En este ejemplo, aprenderá cómo generar el par de claves RSA-OAEP y cómo convertir la clave privada de este par de claves a base64 para que pueda usarlo con OpenSSL, etc. Tenga en cuenta que este proceso también se puede usar para la clave pública que acaba de usar. Para usar el prefijo y el sufijo a continuación:

-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----

NOTA: Este ejemplo está completamente probado en estos navegadores: Chrome, Firefox, Opera, Vivaldi

function arrayBufferToBase64(arrayBuffer) {
    var byteArray = new Uint8Array(arrayBuffer);
    var byteString = '';
    for(var i=0; i < byteArray.byteLength; i++) {
        byteString += String.fromCharCode(byteArray[i]);
    }
    var b64 = window.btoa(byteString);

    return b64;
}

function addNewLines(str) {
    var finalString = '';
    while(str.length > 0) {
        finalString += str.substring(0, 64) + '\n';
        str = str.substring(64);
    }

    return finalString;
}

function toPem(privateKey) {
    var b64 = addNewLines(arrayBufferToBase64(privateKey));
    var pem = "-----BEGIN PRIVATE KEY-----\n" + b64 + "-----END PRIVATE KEY-----";
    
    return pem;
}

// Let's generate the key pair first
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"} // or SHA-512
    },
    true,
    ["encrypt", "decrypt"]
).then(function(keyPair) {
    /* now when the key pair is generated we are going
       to export it from the keypair object in pkcs8
    */
    window.crypto.subtle.exportKey(
        "pkcs8",
        keyPair.privateKey
    ).then(function(exportedPrivateKey) {
        // converting exported private key to PEM format
        var pem = toPem(exportedPrivateKey);
        console.log(pem);
    }).catch(function(err) {
        console.log(err);
    });
});

¡Eso es! Ahora tiene una Clave Privada RSA-OAEP completamente funcional y compatible en formato PEM que puede usar donde quiera. ¡Disfrutar!

Convertir el par de claves PEM a CryptoKey

Entonces, ¿alguna vez se ha preguntado cómo usar su par de claves PEM RSA que fue generado por OpenSSL en la API de criptografía web? Si la respuesta es sí. ¡Genial! Usted va a descubrir.

NOTA: Este proceso también se puede usar para la clave pública, solo necesita cambiar el prefijo y el sufijo para:

-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----

Este ejemplo asume que tiene su par de claves RSA generado en PEM.

function removeLines(str) {
    return str.replace("\n", "");
}

function base64ToArrayBuffer(b64) {
    var byteString = window.atob(b64);
    var byteArray = new Uint8Array(byteString.length);
    for(var i=0; i < byteString.length; i++) {
        byteArray[i] = byteString.charCodeAt(i);
    }

    return byteArray;
}

function pemToArrayBuffer(pem) {
    var b64Lines = removeLines(pem);
    var b64Prefix = b64Lines.replace('-----BEGIN PRIVATE KEY-----', '');
    var b64Final = b64Prefix.replace('-----END PRIVATE KEY-----', '');

    return base64ToArrayBuffer(b64Final);
}

window.crypto.subtle.importKey(
    "pkcs8",
    pemToArrayBuffer(yourprivatekey),
    {
        name: "RSA-OAEP",
        hash: {name: "SHA-256"} // or SHA-512
    },
    true,
    ["decrypt"]
).then(function(importedPrivateKey) {
    console.log(importedPrivateKey);
}).catch(function(err) {
    console.log(err);
});

Y ahora que has terminado! Puedes usar tu clave importada en la API de WebCrypto.



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow