PROJET AUTOBLOG


shaarli-Links

Site original : shaarli-Links

⇐ retour index

Note: javascript AES

mardi 25 juin 2019 à 11:28
// https://stackoverflow.com/questions/51531021/javascript-aes-encryption-and-decryption-advanced-encryption-standard
// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt
const key = await crypto.subtle.generateKey({name: 'AES-GCM', length: 128}, true, ['encrypt', 'decrypt']);
const text = "confidential message";
// IV must be the same length (in bits) as the key
const iv = await crypto.getRandomValues(new Uint8Array(16));
const cyphertext = await crypto.subtle.encrypt({name: 'AES-GCM', tagLength: 32, iv}, key, new TextEncoder().encode(text));

function 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 );
}

function base64ToArrayBuffer(base64) {
    var binary_string =  window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array( len );
    for (var i = 0; i < len; i++)        {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes;
}
base64String=arrayBufferToBase64(cyphertext);
console.log(base64String);
// 'lXjRzQVt9Q1VUVQA38jwCMtGACLaxIxd'

cyphertext2=base64ToArrayBuffer(base64String);

const cleartext = await crypto.subtle.decrypt({name: 'AES-GCM', tagLength: 32, iv}, key, cyphertext);
console.log(new TextDecoder().decode(cleartext));
Permalink