Giter Club home page Giter Club logo

node-rijndael's Introduction

node-rijndael

A native binding to mcrypt's rijndael encryption with a block size of 256 bits. This allows for the encryption and decryption of data generated by Drupal, which uses rijndael-256, despite the AES standard of rijndael-128.

This module enables interfacing between PHP and Node.js, especially where third-party frameworks like Drupal are involved. Drupal uses rijndael-256 by default, and OPENSSL has no support for any block-size of rijndael apart from 128.

Installation

You will need a development version of libmcrypt installed on your system to build node-rijndael.

# for debian derivatives
$ [sudo] apt-get install libmcrypt-dev
# for red hat derivatives
$ [sudo] yum install libmcrypt-devel
# for arch linux
$ [sudo] pacman -S libmcrypt

N.B. if installing node-rijndael fails with an error regarding a "libmcrypt.h" header, this is why.

If you know how to package an external library with a Node Addon, consider submitting a pull request.

npm

$ npm install node-rijndael

github

$ git clone https://github.com/skeggse/node-rijndael.git

Example

A functional example demonstrating PHP and Node compatibility is available in the examples/ directory. A demonstration of the two in a commmand-line example:

$ node
> var key = new Buffer('theonetruesecretkeytorulethemall', 'utf-8').toString('base64');
> var iv = crypto.randomBytes(16).toString('base64');
> iv // we'll use this as the initialization vector for both tests
'UsKguldtsuLm/KrtnctisA=='
> var rijndael = require('./examples/rijndael');
> var plaintext = 'hello, world!';
> var ciphertext = rijndael.encrypt(plaintext, key, iv);
> ciphertext
'50yvJtooiLHUOAbniGgMHmZE18Op99Rhe+Y+G6AjPzM='
> var plaintext = rijndael.decrypt(ciphertext, key, iv);
> plaintext
'hello, world!'

The only changes you'll generally need to make from the example Node implementation are to add the correct padding, as you may need to use PKCS #5 padding or something similar to be compatible with your specific PHP code.

API

As of 0.1.0, node-rijndael will coerce strings into buffers. As of 0.2.0, node-rijndael pads keys and allows key lengths of 16, 24 and 32 bytes.

new Rijndael(key, [options])

The constructor creates a Rijndael object bound to a specific key, with methods for encrypting and decrypting.

The provided key can be either a Buffer or a string, and if a string is provided, the encoding option will be passed to the Buffer constructor.

Options

{
  // the key's encoding (defaults to "binary", but ignored if the key is a buffer)
  "encoding": "binary",
  // the block cipher mode (defaults to Rijndael.MCRYPT_MODE_ECB)
  "mode": Rijndael.MCRYPT_MODE_ECB,
  // the initialization vector (defaults to null, and uses encoding if provided string)
  "iv": null
}

Supported Modes

Rijndael.MCRYPT_MODE_ECB
Rijndael.MCRYPT_MODE_CBC
Rijndael.MCRYPT_MODE_CFB
Rijndael.MCRYPT_MODE_OFB
Rijndael.MCRYPT_MODE_NOFB
Rijndael.MCRYPT_MODE_STREAM

Rijndael#encrypt(plaintext, [input_encoding, [output_encoding]])

Encrypt the provided plaintext with the bound key, and return the encrypted ciphertext. encrypt will return a Buffer by default.

May throw an error if unsupported options provided. Most of the checking should happen in the constructor.

Rijndael#decrypt(ciphertext, [input_encoding, [output_encoding]])

Decrypt the provided ciphertext with the bound key, and return the decrypted plaintext. decrypt will return a Buffer by default.

May throw an error if unsupported options provided. Most of the checking should happen in the constructor.

TODO

A bit more functionality now, needs tests.

See Also

It looks like @tugrul put together a more complete set of bindings for libmcrypt, called node-mcrypt. This module is specifically for rijndael-256. I will not comment on the quality of the bindings.

Unlicense / Public Domain

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>

node-rijndael's People

Contributors

iammapping avatar jamespaulmuir avatar mightydes avatar mscdex avatar skeggse avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

node-rijndael's Issues

Can't find module

Walking through the example steps I get "Error: Symbol rijndael_module not found."

> var key = new Buffer('theonetruesecretkeytorulethemall', 'utf-8').toString('base64');
undefined
> var iv = crypto.randomBytes(16).toString('base64');
undefined
> iv
'StEQKssiMONAQnsyq29X4w=='
> var rijndael = require('./examples/rijndael');

Do I need to build the node module, or another config step? Thanks!

npm failed on node 0.11

gyp_main.py: error: no such option: --no-parallel

gyp ERR! node -v v0.11.13
gyp ERR! node-gyp -v v0.13.0
gyp ERR! not ok 
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the node-rijndael package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild

160-bit block size

There doesn't seem to be any js solution for rijndael-160, would be awesome if this module implemented!

npm install fail in node 4.2.1

npm install node-rijndael --save

Here are the errors i got. Thanks

../node_modules/nan/nan_implementation_12_inl.h:172:66: error: too many arguments to function call, expected at most 2, have 4
  return v8::Signature::New(v8::Isolate::GetCurrent(), receiver, argc, argv);
         ~~~~~~~~~~~~~~~~~~                                      ^~~~~~~~~~
/Users/duncan/.node-gyp/4.2.1/deps/v8/include/v8.h:4675:3: note: 'New' declared here
  static Local<Signature> New(
  ^
In file included from ../src/rijndael.cc:2:
../node_modules/nan/nan.h:165:25: error: redefinition of '_NanEnsureLocal'
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:160:25: note: previous definition is here
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Handle<T> val) {
                        ^
../node_modules/nan/nan.h:253:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(NanNew(v8::Undefined(v8::Isolate::GetCurrent())));
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure [with T = v8::Primitive]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:258:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(NanNew(v8::Null(v8::Isolate::GetCurrent())));
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure [with T = v8::Primitive]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:263:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(NanNew(v8::True(v8::Isolate::GetCurrent())));
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure [with T = v8::Boolean]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:268:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(NanNew(v8::False(v8::Isolate::GetCurrent())));
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure [with T = v8::Boolean]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:500:13: error: no member named 'smalloc' in namespace 'node'
    , node::smalloc::FreeCallback callback
      ~~~~~~^
../node_modules/nan/nan.h:511:12: error: no matching function for call to 'New'
    return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
           ^~~~~~~~~~~~~~~~~
/Users/duncan/.node-gyp/4.2.1/src/node_buffer.h:31:40: note: candidate function not viable: no known conversion from 'uint32_t' (aka 'unsigned int') to 'enum encoding' for 3rd argument
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
/Users/duncan/.node-gyp/4.2.1/src/node_buffer.h:43:40: note: candidate function not viable: 2nd argument ('const char *') would lose const qualifier
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
/Users/duncan/.node-gyp/4.2.1/src/node_buffer.h:28:40: note: candidate function not viable: requires 2 arguments, but 3 were provided
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate, size_t length);
                                       ^
/Users/duncan/.node-gyp/4.2.1/src/node_buffer.h:36:40: note: candidate function not viable: requires 5 arguments, but 3 were provided
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
In file included from ../src/rijndael.cc:2:
../node_modules/nan/nan.h:515:12: error: no viable conversion from 'v8::MaybeLocal<v8::Object>' to 'v8::Local<v8::Object>'
    return node::Buffer::New(v8::Isolate::GetCurrent(), size);
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/duncan/.node-gyp/4.2.1/deps/v8/include/v8.h:210:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'v8::MaybeLocal<v8::Object>' to 'const v8::Local<v8::Object> &' for 1st argument
class Local {
      ^
/Users/duncan/.node-gyp/4.2.1/deps/v8/include/v8.h:210:7: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'v8::MaybeLocal<v8::Object>' to 'v8::Local<v8::Object> &&' for 1st argument
class Local {
      ^
/Users/duncan/.node-gyp/4.2.1/deps/v8/include/v8.h:214:13: note: candidate template ignored: could not match 'Local' against 'MaybeLocal'
  V8_INLINE Local(Local<S> that)
            ^
/Users/duncan/.node-gyp/4.2.1/deps/v8/include/v8.h:326:13: note: candidate template ignored: could not match 'S *' against 'v8::MaybeLocal<v8::Object>'
  V8_INLINE Local(S* that)
            ^
In file included from ../src/rijndael.cc:2:
../node_modules/nan/nan.h:522:26: error: no member named 'Use' in namespace 'node::Buffer'
    return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size);
           ~~~~~~~~~~~~~~^
../node_modules/nan/nan.h:1339:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(NanNew(handle)->Get(kCallbackIndex)
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure [with T = v8::Function]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:1354:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(node::MakeCallback(
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure [with T = v8::Value]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
../node_modules/nan/nan.h:1427:12: error: no matching function for call to '_NanEnsureLocal'
    return NanEscapeScope(handle->Get(NanNew(key)).As<v8::Object>());
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:239:43: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val))
                                          ^~~~~~~~~~~~~~~
../node_modules/nan/nan.h:165:25: note: candidate template ignored: substitution failure [with T = v8::Object]
NAN_INLINE v8::Local<T> _NanEnsureLocal(v8::Local<T> val) {
                        ^
13 errors generated.

No Tests

Need to write some, see test/ to start.

error C2146

Hello all!

when I to try: "npm install node-rijndael" I have this error (It seems a compilation error):

c:\users\equipo.node-gyp\0.12.4\deps\uv\include\uv-win.h(251): error C2146: error de sintaxis : falta ';' delante del identificador 'srwlock_' [c:\WSbrainProyect\node_modules\node-rijndael\build\binding.sln]
c:\users\equipo.node-gyp\0.12.4\deps\uv\include\uv-win.h(251): error C4430: falta el especificador de tipo; se presupone int. Nota: C++ no admite default-int [c:\WSbrainProyect\node_modules\node-rijndael\build\binding.sln] c:\users\equipo.node-gyp\0.12.4\deps\uv\include\uv-win.h(251): error C4430: falta el especificador de tipo; se presupone int. Nota: C++ no admite default-int [c:\WSbrainProyect\node_modules\node-rijndael\build\binding.sln] ..\src\rijndael.cc(9): fatal error C1083: No se puede abrir el archivo incluir: 'mcrypt.h': No such file or directory [c:\WSbrainProyect\node_modules\node-rijndael\build\binding.sln]

Can you help me?
Thanks

Can't able to decrypt the data encrypted in C#.net.

//.net code
//Sorry if you are not from .net background

using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;

namespace Encrypt
{
static class Program
{

    /// <summary>
    /// Main Entry of the Application
    /// </summary>
    /// <param name="args"></param>
    [HandleProcessCorruptedStateExceptions]
    static void Main(string[] args)
    {
        string original = "Hello, World!";
        try
        {
            byte [] cipher = EncryptString(original);
            Console.WriteLine("Encrypted cipher is :{0}",Convert.ToBase64String(cipher));
            Console.ReadKey();
        }
        catch (CryptographicException exception)
        {
            Trace.Write(exception);
        }
    }

    private static byte[] EncryptString(string message)
    {
        if (message == null || message.Length <= 0)
        throw  new ArgumentNullException(message);
        //Create Cypher algo 
        //note default paddingmode is PKSC7
        RijndaelManaged rijndael = new RijndaelManaged {KeySize = 256};
        rijndael.GenerateIV();
        rijndael.GenerateKey();


        Console.WriteLine("Rindael IV is {0}", Convert.ToBase64String(rijndael.IV));
        Console.WriteLine("Rindeal Key is {0}", Convert.ToBase64String(rijndael.Key));

        ICryptoTransform crypto = rijndael.CreateEncryptor();

        using (MemoryStream memoryStream = new MemoryStream())
        {
            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, crypto, CryptoStreamMode.Write))
            {
                using (StreamWriter sw = new StreamWriter(cryptoStream))
                {
                    sw.Write(message);
                    //sw.Flush();
                }
                return memoryStream.ToArray();
            }

        }
    }
}

}

//output
Rindael IV is +VQYSNRSJ4jskZW+ChX13A==
Rindeal Key is 4Mc8auw+ZJrRZAqRkcQfU2YftnGwgqHHt2aCCpn8TBA=
Encrypted cipher is :aKvTCNYg8s9G06uJb9WW8g==

Note - All the data here is base64 string

//nodejs code to decrypt

var iv = '+VQYSNRSJ4jskZW+ChX13A==';
var key = '4Mc8auw+ZJrRZAqRkcQfU2YftnGwgqHHt2aCCpn8TBA=';
var rijndael = require('/home/root-007/node_modules/node-rijndael/examples/rijndael.js');
var encrypteddata = 'aKvTCNYg8s9G06uJb9WW8g==';
var plaintext = rijndael.decrypt(encrypteddata, key, iv);
console.log(plaintext);

//output
�P!8£¢H4mΪt%ª �!&��À�Ï°�
î? �

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.