Skip to content

Commit 42bda05

Browse files
seishunindutny
authored andcommitted
crypto: add RSA encryption
Reviewed-By: Fedor Indutny <fedor@indutny.com>
1 parent 93f3b64 commit 42bda05

5 files changed

Lines changed: 235 additions & 0 deletions

File tree

‎doc/api/crypto.markdown‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -593,6 +593,22 @@ Exports the encoded public key from the supplied SPKAC.
593593

594594
Exports the encoded challenge associated with the SPKAC.
595595

596+
## crypto.publicEncrypt(public_key, buffer)
597+
598+
Encrypts `buffer` with `public_key`. Only RSA is currently supported.
599+
600+
## crypto.privateDecrypt(private_key, buffer)
601+
602+
Decrypts `buffer` with `private_key`.
603+
604+
`private_key` can be an object or a string. If `private_key` is a string, it is
605+
treated as the key with no passphrase.
606+
607+
`private_key`:
608+
609+
* `key` : A string holding the PEM encoded private key
610+
* `passphrase` : A string of passphrase for the private key
611+
596612
## crypto.DEFAULT_ENCODING
597613

598614
The default encoding to use for functions that can take either strings

‎lib/crypto.js‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,16 @@ Verify.prototype.verify = function(object, signature, sigEncoding) {
355355
return this._handle.verify(toBuf(object), toBuf(signature, sigEncoding));
356356
};
357357

358+
exports.publicEncrypt = function(object, buffer) {
359+
return binding.publicEncrypt(toBuf(object), buffer);
360+
};
361+
362+
exports.privateDecrypt = function(options, buffer) {
363+
var key = options.key || options;
364+
var passphrase = options.passphrase || null;
365+
return binding.privateDecrypt(toBuf(key), buffer, passphrase);
366+
};
367+
358368

359369

360370
exports.createDiffieHellman = exports.DiffieHellman = DiffieHellman;

‎src/node_crypto.cc‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ static const char PUBLIC_KEY_PFX[] = "-----BEGIN PUBLIC KEY-----";
6565
static const int PUBLIC_KEY_PFX_LEN = sizeof(PUBLIC_KEY_PFX) - 1;
6666
static const char PUBRSA_KEY_PFX[] = "-----BEGIN RSA PUBLIC KEY-----";
6767
static const int PUBRSA_KEY_PFX_LEN = sizeof(PUBRSA_KEY_PFX) - 1;
68+
static const char CERTIFICATE_PFX[] = "-----BEGIN CERTIFICATE-----";
69+
static const int CERTIFICATE_PFX_LEN = sizeof(CERTIFICATE_PFX) - 1;
70+
6871
static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
6972
| ASN1_STRFLGS_ESC_MSB
7073
| XN_FLAG_SEP_MULTILINE
@@ -3544,6 +3547,139 @@ void Verify::VerifyFinal(const FunctionCallbackInfo<Value>& args) {
35443547
}
35453548

35463549

3550+
template <PublicKeyCipher::Operation operation,
3551+
PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
3552+
PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
3553+
bool PublicKeyCipher::Cipher(const char* key_pem,
3554+
int key_pem_len,
3555+
const char* passphrase,
3556+
const unsigned char* data,
3557+
int len,
3558+
unsigned char** out,
3559+
size_t* out_len) {
3560+
EVP_PKEY* pkey = NULL;
3561+
EVP_PKEY_CTX* ctx = NULL;
3562+
BIO* bp = NULL;
3563+
X509* x509 = NULL;
3564+
bool fatal = true;
3565+
3566+
bp = BIO_new(BIO_s_mem());
3567+
if (bp == NULL)
3568+
goto exit;
3569+
3570+
if (!BIO_write(bp, key_pem, key_pem_len))
3571+
goto exit;
3572+
3573+
// Check if this is a PKCS#8 or RSA public key before trying as X.509 and
3574+
// private key.
3575+
if (operation == kEncrypt &&
3576+
strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
3577+
pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL);
3578+
if (pkey == NULL)
3579+
goto exit;
3580+
} else if (operation == kEncrypt &&
3581+
strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
3582+
RSA* rsa = PEM_read_bio_RSAPublicKey(bp, NULL, NULL, NULL);
3583+
if (rsa) {
3584+
pkey = EVP_PKEY_new();
3585+
if (pkey)
3586+
EVP_PKEY_set1_RSA(pkey, rsa);
3587+
RSA_free(rsa);
3588+
}
3589+
if (pkey == NULL)
3590+
goto exit;
3591+
} else if (operation == kEncrypt &&
3592+
strncmp(key_pem, CERTIFICATE_PFX, CERTIFICATE_PFX_LEN) == 0) {
3593+
x509 = PEM_read_bio_X509(bp, NULL, CryptoPemCallback, NULL);
3594+
if (x509 == NULL)
3595+
goto exit;
3596+
3597+
pkey = X509_get_pubkey(x509);
3598+
if (pkey == NULL)
3599+
goto exit;
3600+
} else {
3601+
pkey = PEM_read_bio_PrivateKey(bp,
3602+
NULL,
3603+
CryptoPemCallback,
3604+
const_cast<char*>(passphrase));
3605+
if (pkey == NULL)
3606+
goto exit;
3607+
}
3608+
3609+
ctx = EVP_PKEY_CTX_new(pkey, NULL);
3610+
if (!ctx)
3611+
goto exit;
3612+
if (EVP_PKEY_cipher_init(ctx) <= 0)
3613+
goto exit;
3614+
if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0)
3615+
goto exit;
3616+
if (EVP_PKEY_cipher(ctx, NULL, out_len, data, len) <= 0)
3617+
goto exit;
3618+
3619+
*out = new unsigned char[*out_len];
3620+
3621+
if (EVP_PKEY_cipher(ctx, *out, out_len, data, len) <= 0)
3622+
goto exit;
3623+
3624+
fatal = false;
3625+
3626+
exit:
3627+
if (pkey != NULL)
3628+
EVP_PKEY_free(pkey);
3629+
if (bp != NULL)
3630+
BIO_free_all(bp);
3631+
if (ctx != NULL)
3632+
EVP_PKEY_CTX_free(ctx);
3633+
3634+
return !fatal;
3635+
}
3636+
3637+
3638+
template <PublicKeyCipher::Operation operation,
3639+
PublicKeyCipher::EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
3640+
PublicKeyCipher::EVP_PKEY_cipher_t EVP_PKEY_cipher>
3641+
void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
3642+
Environment* env = Environment::GetCurrent(args.GetIsolate());
3643+
HandleScope scope(env->isolate());
3644+
3645+
ASSERT_IS_BUFFER(args[0]);
3646+
char* kbuf = Buffer::Data(args[0]);
3647+
ssize_t klen = Buffer::Length(args[0]);
3648+
3649+
ASSERT_IS_BUFFER(args[1]);
3650+
char* buf = Buffer::Data(args[1]);
3651+
ssize_t len = Buffer::Length(args[1]);
3652+
3653+
String::Utf8Value passphrase(args[2]);
3654+
3655+
unsigned char* out_value = NULL;
3656+
size_t out_len = -1;
3657+
3658+
bool r = Cipher<operation, EVP_PKEY_cipher_init, EVP_PKEY_cipher>(
3659+
kbuf,
3660+
klen,
3661+
args.Length() >= 3 && !args[2]->IsNull() ? *passphrase : NULL,
3662+
reinterpret_cast<const unsigned char*>(buf),
3663+
len,
3664+
&out_value,
3665+
&out_len);
3666+
3667+
if (out_len <= 0 || !r) {
3668+
delete[] out_value;
3669+
out_value = NULL;
3670+
out_len = 0;
3671+
if (!r) {
3672+
return ThrowCryptoError(env,
3673+
ERR_get_error());
3674+
}
3675+
}
3676+
3677+
args.GetReturnValue().Set(
3678+
Buffer::New(env, reinterpret_cast<char*>(out_value), out_len));
3679+
delete[] out_value;
3680+
}
3681+
3682+
35473683
void DiffieHellman::Initialize(Environment* env, Handle<Object> target) {
35483684
Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(), New);
35493685

@@ -4730,6 +4866,16 @@ void InitCrypto(Handle<Object> target,
47304866
NODE_SET_METHOD(target, "getSSLCiphers", GetSSLCiphers);
47314867
NODE_SET_METHOD(target, "getCiphers", GetCiphers);
47324868
NODE_SET_METHOD(target, "getHashes", GetHashes);
4869+
NODE_SET_METHOD(target,
4870+
"publicEncrypt",
4871+
PublicKeyCipher::Cipher<PublicKeyCipher::kEncrypt,
4872+
EVP_PKEY_encrypt_init,
4873+
EVP_PKEY_encrypt>);
4874+
NODE_SET_METHOD(target,
4875+
"privateDecrypt",
4876+
PublicKeyCipher::Cipher<PublicKeyCipher::kDecrypt,
4877+
EVP_PKEY_decrypt_init,
4878+
EVP_PKEY_decrypt>);
47334879
}
47344880

47354881
} // namespace crypto

‎src/node_crypto.h‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,35 @@ class Verify : public SignBase {
559559
}
560560
};
561561

562+
class PublicKeyCipher {
563+
public:
564+
typedef int (*EVP_PKEY_cipher_init_t)(EVP_PKEY_CTX *ctx);
565+
typedef int (*EVP_PKEY_cipher_t)(EVP_PKEY_CTX *ctx,
566+
unsigned char *out, size_t *outlen,
567+
const unsigned char *in, size_t inlen);
568+
569+
enum Operation {
570+
kEncrypt,
571+
kDecrypt
572+
};
573+
574+
template <Operation operation,
575+
EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
576+
EVP_PKEY_cipher_t EVP_PKEY_cipher>
577+
static bool Cipher(const char* key_pem,
578+
int key_pem_len,
579+
const char* passphrase,
580+
const unsigned char* data,
581+
int len,
582+
unsigned char** out,
583+
size_t* out_len);
584+
585+
template <Operation operation,
586+
EVP_PKEY_cipher_init_t EVP_PKEY_cipher_init,
587+
EVP_PKEY_cipher_t EVP_PKEY_cipher>
588+
static void Cipher(const v8::FunctionCallbackInfo<v8::Value>& args);
589+
};
590+
562591
class DiffieHellman : public BaseObject {
563592
public:
564593
~DiffieHellman() {

‎test/simple/test-crypto.js‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -823,6 +823,40 @@ var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' +
823823
var bad_dh = crypto.createDiffieHellman(p, 'hex');
824824
assert.equal(bad_dh.verifyError, constants.DH_NOT_SUITABLE_GENERATOR);
825825

826+
// Test RSA encryption/decryption
827+
(function() {
828+
var input = 'I AM THE WALRUS';
829+
var bufferToEncrypt = new Buffer(input);
830+
831+
var encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt);
832+
833+
var decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer);
834+
assert.equal(input, decryptedBuffer.toString());
835+
836+
var decryptedBufferWithPassword = crypto.privateDecrypt({
837+
key: rsaKeyPemEncrypted,
838+
passphrase: 'password'
839+
}, encryptedBuffer);
840+
assert.equal(input, decryptedBufferWithPassword.toString());
841+
842+
encryptedBuffer = crypto.publicEncrypt(certPem, bufferToEncrypt);
843+
844+
decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer);
845+
assert.equal(input, decryptedBuffer.toString());
846+
847+
encryptedBuffer = crypto.publicEncrypt(keyPem, bufferToEncrypt);
848+
849+
decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer);
850+
assert.equal(input, decryptedBuffer.toString());
851+
852+
assert.throws(function() {
853+
crypto.privateDecrypt({
854+
key: rsaKeyPemEncrypted,
855+
passphrase: 'wrong'
856+
}, encryptedBuffer);
857+
});
858+
})();
859+
826860
// Test RSA key signing/verification
827861
var rsaSign = crypto.createSign('RSA-SHA1');
828862
var rsaVerify = crypto.createVerify('RSA-SHA1');

0 commit comments

Comments
 (0)