Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
Crypto: adding ability to turn off automatic PKCS padding
Browse files Browse the repository at this point in the history
  • Loading branch information
KiNgMaR authored and piscisaureus committed Jan 18, 2012
1 parent ad42a82 commit 0ca3018
Show file tree
Hide file tree
Showing 3 changed files with 188 additions and 11 deletions.
12 changes: 12 additions & 0 deletions doc/api/crypto.markdown
Expand Up @@ -120,6 +120,12 @@ Returns any remaining enciphered contents, with `output_encoding` being one of:

Note: `cipher` object can not be used after `final()` method been called.

### cipher.setAutoPadding(auto_padding=true)

You can disable automatic padding of the input data to block size. If `auto_padding` is false,
the length of the entire input data must be a multiple of the cipher's block size or `final` will fail.
Useful for non-standard padding, e.g. using `0x0` instead of PKCS padding. You must call this before `cipher.final`.


### crypto.createDecipher(algorithm, password)

Expand Down Expand Up @@ -147,6 +153,12 @@ Defaults to `'binary'`.

Note: `decipher` object can not be used after `final()` method been called.

### decipher.setAutoPadding(auto_padding=true)

You can disable auto padding if the data has been encrypted without standard block padding to prevent
`decipher.final` from checking and removing it. Can only work if the input data's length is a multiple of the
ciphers block size. You must call this before streaming data to `decipher.update`.


### crypto.createSign(algorithm)

Expand Down
68 changes: 57 additions & 11 deletions src/node_crypto.cc
Expand Up @@ -1882,6 +1882,7 @@ class Cipher : public ObjectWrap {
NODE_SET_PROTOTYPE_METHOD(t, "init", CipherInit);
NODE_SET_PROTOTYPE_METHOD(t, "initiv", CipherInitIv);
NODE_SET_PROTOTYPE_METHOD(t, "update", CipherUpdate);
NODE_SET_PROTOTYPE_METHOD(t, "setAutoPadding", SetAutoPadding);
NODE_SET_PROTOTYPE_METHOD(t, "final", CipherFinal);

target->Set(String::NewSymbol("Cipher"), t->GetFunction());
Expand Down Expand Up @@ -1945,7 +1946,6 @@ class Cipher : public ObjectWrap {
return true;
}


int CipherUpdate(char* data, int len, unsigned char** out, int* out_len) {
if (!initialised_) return 0;
*out_len=len+EVP_CIPHER_CTX_block_size(&ctx);
Expand All @@ -1955,19 +1955,24 @@ class Cipher : public ObjectWrap {
return 1;
}

int SetAutoPadding(bool auto_padding) {
if (!initialised_) return 0;
return EVP_CIPHER_CTX_set_padding(&ctx, auto_padding ? 1 : 0);
}

int CipherFinal(unsigned char** out, int *out_len) {
if (!initialised_) return 0;
*out = new unsigned char[EVP_CIPHER_CTX_block_size(&ctx)];
EVP_CipherFinal_ex(&ctx,*out,out_len);
int r = EVP_CipherFinal_ex(&ctx,*out, out_len);
EVP_CIPHER_CTX_cleanup(&ctx);
initialised_ = false;
return 1;
return r;
}


protected:

static Handle<Value> New (const Arguments& args) {
static Handle<Value> New(const Arguments& args) {
HandleScope scope;

Cipher *cipher = new Cipher();
Expand Down Expand Up @@ -2155,6 +2160,15 @@ class Cipher : public ObjectWrap {
return scope.Close(outString);
}

static Handle<Value> SetAutoPadding(const Arguments& args) {
HandleScope scope;
Cipher *cipher = ObjectWrap::Unwrap<Cipher>(args.This());

cipher->SetAutoPadding(args.Length() < 1 || args[0]->BooleanValue());

return Undefined();
}

static Handle<Value> CipherFinal(const Arguments& args) {
Cipher *cipher = ObjectWrap::Unwrap<Cipher>(args.This());

Expand All @@ -2169,10 +2183,18 @@ class Cipher : public ObjectWrap {
int r = cipher->CipherFinal(&out_value, &out_len);

assert(out_value != NULL);
assert(out_len != -1);
assert(out_len != -1 || r == 0);

if (out_len == 0 || r == 0) {
return scope.Close(String::New(""));
// out_value always get allocated.
delete[] out_value;
if (r == 0) {
Local<Value> exception = Exception::TypeError(
String::New("CipherFinal fail"));
return ThrowException(exception);
} else {
return scope.Close(String::New(""));
}
}

enum encoding enc = ParseEncoding(args[0], BINARY);
Expand Down Expand Up @@ -2247,7 +2269,9 @@ class Decipher : public ObjectWrap {
NODE_SET_PROTOTYPE_METHOD(t, "initiv", DecipherInitIv);
NODE_SET_PROTOTYPE_METHOD(t, "update", DecipherUpdate);
NODE_SET_PROTOTYPE_METHOD(t, "final", DecipherFinal<false>);
// This is completely undocumented:
NODE_SET_PROTOTYPE_METHOD(t, "finaltol", DecipherFinal<true>);
NODE_SET_PROTOTYPE_METHOD(t, "setAutoPadding", SetAutoPadding);

target->Set(String::NewSymbol("Decipher"), t->GetFunction());
}
Expand Down Expand Up @@ -2330,9 +2354,16 @@ class Decipher : public ObjectWrap {
return 1;
}

int SetAutoPadding(bool auto_padding) {
if (!initialised_) return 0;
return EVP_CIPHER_CTX_set_padding(&ctx, auto_padding ? 1 : 0);
}

// coverity[alloc_arg]
template <bool TOLERATE_PADDING>
int DecipherFinal(unsigned char** out, int *out_len) {
int r;

if (!initialised_) {
*out_len = 0;
*out = NULL;
Expand All @@ -2341,13 +2372,13 @@ class Decipher : public ObjectWrap {

*out = new unsigned char[EVP_CIPHER_CTX_block_size(&ctx)];
if (TOLERATE_PADDING) {
local_EVP_DecryptFinal_ex(&ctx,*out,out_len);
r = local_EVP_DecryptFinal_ex(&ctx,*out,out_len);
} else {
EVP_CipherFinal_ex(&ctx,*out,out_len);
r = EVP_CipherFinal_ex(&ctx,*out,out_len);
}
EVP_CIPHER_CTX_cleanup(&ctx);
initialised_ = false;
return 1;
return r;
}


Expand Down Expand Up @@ -2580,6 +2611,15 @@ class Decipher : public ObjectWrap {

}

static Handle<Value> SetAutoPadding(const Arguments& args) {
HandleScope scope;
Decipher *cipher = ObjectWrap::Unwrap<Decipher>(args.This());

cipher->SetAutoPadding(args.Length() < 1 || args[0]->BooleanValue());

return Undefined();
}

template <bool TOLERATE_PADDING>
static Handle<Value> DecipherFinal(const Arguments& args) {
HandleScope scope;
Expand All @@ -2596,8 +2636,14 @@ class Decipher : public ObjectWrap {
assert(out_len != -1);

if (out_len == 0 || r == 0) {
delete[] out_value;
return scope.Close(String::New(""));
delete [] out_value; // allocated even if out_len == 0
if (r == 0) {
Local<Value> exception = Exception::TypeError(
String::New("DecipherFinal fail"));
return ThrowException(exception);
} else {
return scope.Close(String::New(""));
}
}

if (args.Length() == 0 || !args[0]->IsString()) {
Expand Down
119 changes: 119 additions & 0 deletions test/simple/test-crypto-padding.js
@@ -0,0 +1,119 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// 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 OR COPYRIGHT HOLDERS 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.

var common = require('../common');
var assert = require('assert');

try {
var crypto = require('crypto');
} catch (e) {
console.log('Not compiled with OPENSSL support.');
process.exit();
}


/*
* Input data
*/

var ODD_LENGTH_PLAIN = 'Hello node world!',
EVEN_LENGTH_PLAIN = 'Hello node world!AbC09876dDeFgHi';

var KEY_PLAIN = 'S3c.r.e.t.K.e.Y!',
IV_PLAIN = 'blahFizz2011Buzz';

var CIPHER_NAME = 'aes-128-cbc';


/*
* Expected result data
*/

// echo -n 'Hello node world!' | openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 -iv 626c616846697a7a3230313142757a7a | xxd -p -c256
var ODD_LENGTH_ENCRYPTED = '7f57859550d4d2fdb9806da2a750461a9fe77253cd1cbd4b07beee4e070d561f';

// echo -n 'Hello node world!AbC09876dDeFgHi' | openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 -iv 626c616846697a7a3230313142757a7a | xxd -p -c256
var EVEN_LENGTH_ENCRYPTED = '7f57859550d4d2fdb9806da2a750461ab46e71b3d78ebe2d9684dfc87f7575b9886119866912cb8c7bcaf76c5ebc2378';

// echo -n 'Hello node world!AbC09876dDeFgHi' | openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 -iv 626c616846697a7a3230313142757a7a -nopad | xxd -p -c256
var EVEN_LENGTH_ENCRYPTED_NOPAD = '7f57859550d4d2fdb9806da2a750461ab46e71b3d78ebe2d9684dfc87f7575b9';


/*
* Helper wrappers
*/

function enc(plain, pad) {
var encrypt = crypto.createCipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN);
encrypt.setAutoPadding(pad);
var hex = encrypt.update(plain, 'ascii', 'hex');
hex += encrypt.final('hex');
return hex;
}

function dec(encd, pad) {
var decrypt = crypto.createDecipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN);
decrypt.setAutoPadding(pad);
var plain = decrypt.update(encd, 'hex');
plain += decrypt.final('binary');
return plain;
}


/*
* Test encryption
*/

assert.equal(enc(ODD_LENGTH_PLAIN, true), ODD_LENGTH_ENCRYPTED);
assert.equal(enc(EVEN_LENGTH_PLAIN, true), EVEN_LENGTH_ENCRYPTED);

assert.throws(function() {
// input must have block length %
enc(ODD_LENGTH_PLAIN, false);
});

assert.doesNotThrow(function() {
assert.equal(enc(EVEN_LENGTH_PLAIN, false), EVEN_LENGTH_ENCRYPTED_NOPAD);
});


/*
* Test decryption
*/

assert.equal(dec(ODD_LENGTH_ENCRYPTED, true), ODD_LENGTH_PLAIN);
assert.equal(dec(EVEN_LENGTH_ENCRYPTED, true), EVEN_LENGTH_PLAIN);

assert.doesNotThrow(function() {
// returns including original padding
assert.equal(dec(ODD_LENGTH_ENCRYPTED, false).length, 32);
assert.equal(dec(EVEN_LENGTH_ENCRYPTED, false).length, 48);
});

assert.throws(function() {
// must have at least 1 byte of padding (PKCS):
assert.equal(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, true), EVEN_LENGTH_PLAIN);
});

assert.doesNotThrow(function() {
// no-pad encrypted string should return the same:
assert.equal(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, false), EVEN_LENGTH_PLAIN);
});

0 comments on commit 0ca3018

Please sign in to comment.