xiongyihui / notes

Notes
https://xiongyihui.github.io/notes/
3 stars 0 forks source link

AES Encryption & Decryption in Python & JavaScript #28

Open xiongyihui opened 5 years ago

xiongyihui commented 5 years ago

AES CTR Mode

Python

import base64
import random

from Crypto.Cipher import AES
from Crypto.Util import Counter

def encrypt(key, counter, data):
    aes = AES.new(key, AES.MODE_CTR,  counter=Counter.new(128, initial_value=counter))
    encrypted = aes.encrypt(data)
    return {'id': counter, 'data': base64.b64encode(encrypted).decode()}

def decrypt(key, counter, data):
    data = base64.b64decode(data.encode())
    aes = AES.new(key, AES.MODE_CTR,  counter=Counter.new(128, initial_value=counter))
    decrypted = aes.decrypt(data)
    return decrypted

key = b'\x00' * 16
counter =1  # random.SystemRandom().randint(0, 1 << 15)
data = '1234567890'
message = encrypt(key, counter, data)
print((data, message))

print(decrypt(key, counter, message['data']))

JS on browser

function str2array(str) {
    var buf = new Uint8Array(str.length);
    for (var i = 0; i < str.length; i++) {
        buf[i] = str.charCodeAt(i);
    }
    return buf;
}

function array2str(bytes) {
    return String.fromCharCode.apply(null, bytes);
}

async function generateKey(str) {
            str = str.substring(0, 16);
            var rawKey = new Uint8Array(16);
            for (var i = 0; i < str.length; i++) {
                rawKey[i] = str.charCodeAt(i);
            }

            return await crypto.subtle.importKey(
                "raw",
                rawKey,
                "AES-CTR",
                true,
                ["encrypt", "decrypt"]

async function generateKey(str) {
    str = str.substring(0, 16);
    var rawKey = new Uint8Array(16);
    for (var i = 0; i < str.length; i++) {
        rawKey[i] = str.charCodeAt(i);
    }

    return await crypto.subtle.importKey(
        "raw",
        rawKey,
        "AES-CTR",
        true,
        ["encrypt", "decrypt"]
    );
}

function getCounter(n) {
    var counter = new Uint8Array(16);
    for (var i = 15; i >= 0; --i) {
        counter[i] = n % 256;
        n = n / 256;
    }
    return counter;
}

async function decrypt(counter, seed, b64str) {
    var array = str2array(atob(b64str));

    var key = await generateKey(seed);
    var decrypted = await window.crypto.subtle.decrypt(
        {
            name: "AES-CTR",
            counter,
            length: 64
        },
        key,
        array,
        );

    return array2str(new Uint8Array(decrypted));
}

async function encrypt(counter, seed, str) {
    var array = str2array(str);

    var key = await generateKey(seed);
    var encrypetd = await window.crypto.subtle.encrypt(
        {
            name: "AES-CTR",
            counter,
            length: 64
        },
        key,
        array
    );

    return btoa(array2str(new Uint8Array(encrypetd)));
}

var key = '';
var n = 1;  // Math.floor(Math.random() * 10000);
var counter = getCounter(n);
encrypt(counter, key, '0123456789').then(encrypted => {
    console.log(encrypted);
});

aes-js

function str2array(str) {
    var buf = new Uint8Array(str.length);
    for (var i = 0; i < str.length; i++) {
        buf[i] = str.charCodeAt(i);
    }
    return buf;
}

function array2str(bytes) {
    return String.fromCharCode.apply(null, bytes);
}

key = str2array('0123456789012345');
var n = 1;   // Math.floor(Math.random() * 10000);
var aesCtr = new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(n));
var msg = '0123456789'
var encrypted = aesCtr.encrypt(str2array(msg));