|
| 1 | +#include <napi.h> |
| 2 | +#include <stdio.h> |
| 3 | +#include "wolfssl/options.h" |
| 4 | +#include <wolfssl/wolfcrypt/settings.h> |
| 5 | +#include <wolfssl/wolfcrypt/aes.h> |
| 6 | + |
| 7 | +using namespace Napi; |
| 8 | + |
| 9 | +typedef struct WrappedKey |
| 10 | +{ |
| 11 | + Aes aes[1]; |
| 12 | + uint8_t key[32]; |
| 13 | + uint8_t iv[16]; |
| 14 | +} WrappedKey; |
| 15 | + |
| 16 | +Napi::Number MakeAes(const Napi::CallbackInfo& info) { |
| 17 | + int ret = 0; |
| 18 | + Napi::Env env = info.Env(); |
| 19 | + WrappedKey* key = (WrappedKey*)(info[0].As<Napi::Uint8Array>().Data()); |
| 20 | + memcpy( key->key, (info[1].As<Napi::Uint8Array>().Data()), 32 ); |
| 21 | + memcpy( key->iv, (info[2].As<Napi::Uint8Array>().Data()), 16 ); |
| 22 | + |
| 23 | + //ret = wc_AesInit( key->aes, NULL, INVALID_DEVID ); |
| 24 | + |
| 25 | + return Napi::Number::New( env, ret ); |
| 26 | +} |
| 27 | + |
| 28 | +Napi::Number Encrypt(const Napi::CallbackInfo& info) { |
| 29 | + int ret; |
| 30 | + Napi::Env env = info.Env(); |
| 31 | + WrappedKey* key = (WrappedKey*)(info[0].As<Napi::Uint8Array>().Data()); |
| 32 | + uint8_t* out = info[1].As<Napi::Uint8Array>().Data(); |
| 33 | + uint8_t* in = info[2].As<Napi::Uint8Array>().Data(); |
| 34 | + int length = info[3].As<Napi::Number>().Int32Value(); |
| 35 | + |
| 36 | + ret = wc_AesSetKey( key->aes, key->key, AES_256_KEY_SIZE, key->iv, AES_ENCRYPTION ); |
| 37 | + |
| 38 | + if ( ret == 0 ) |
| 39 | + ret = wc_AesCbcEncrypt( key->aes, out, in, length ); |
| 40 | + |
| 41 | + return Napi::Number::New( env, ret ); |
| 42 | +} |
| 43 | + |
| 44 | +Napi::Number Decrypt(const Napi::CallbackInfo& info) |
| 45 | +{ |
| 46 | + int ret; |
| 47 | + Napi::Env env = info.Env(); |
| 48 | + WrappedKey* key = (WrappedKey*)(info[0].As<Napi::Uint8Array>().Data()); |
| 49 | + uint8_t* out = info[1].As<Napi::Uint8Array>().Data(); |
| 50 | + uint8_t* in = info[2].As<Napi::Uint8Array>().Data(); |
| 51 | + int length = info[3].As<Napi::Number>().Int32Value(); |
| 52 | + |
| 53 | + ret = wc_AesSetKey( key->aes, key->key, AES_256_KEY_SIZE, key->iv, AES_DECRYPTION ); |
| 54 | + |
| 55 | + if ( ret == 0 ) |
| 56 | + ret = wc_AesCbcDecrypt( key->aes, out, in, length ); |
| 57 | + |
| 58 | + return Napi::Number::New( env, ret ); |
| 59 | +} |
| 60 | + |
| 61 | +Napi::Object Init(Napi::Env env, Napi::Object exports) { |
| 62 | + exports.Set(Napi::String::New(env, "MakeAes"), Napi::Function::New(env, MakeAes)); |
| 63 | + exports.Set(Napi::String::New(env, "Encrypt"), Napi::Function::New(env, Encrypt)); |
| 64 | + exports.Set(Napi::String::New(env, "Decrypt"), Napi::Function::New(env, Decrypt)); |
| 65 | + |
| 66 | + return exports; |
| 67 | +} |
| 68 | + |
| 69 | +NODE_API_MODULE( addon, Init ) |
0 commit comments