A native implementation of TLS (and various other cryptographic tools) in JavaScript.
The Forge software is a fully native implementation of the TLS protocol in JavaScript, a set of cryptography utilities, and a set of tools for developing Web Apps that utilize many network resources.
Forge is fast. Benchmarks against other popular JavaScript cryptography libraries can be found here:
- http://dominictarr.github.io/crypto-bench/
- http://cryptojs.altervista.org/test/simulate-threading-speed_test.html
Note: Please see the Security Considerations section before using packaging systems and pre-built files.
Forge uses a CommonJS module structure with a build process for browser bundles. The older 0.6.x branch with standalone files is available but will not be regularly updated.
If you want to use forge with Node.js, it is available through npm
:
https://www.npmjs.com/package/node-forge
Installation:
npm install node-forge
You can then use forge as a regular module:
var forge = require('node-forge');
The npm package includes pre-built forge.min.js
, forge.all.min.js
, and
prime.worker.min.js
using the UMD format.
To use it via jsDelivr include this in your html:
<script src="https://cdn.jsdelivr.net/npm/node-forge@1.0.0/dist/forge.min.js"></script>
To use it via unpkg include this in your html:
<script src="https://unpkg.com/node-forge@1.0.0/dist/forge.min.js"></script>
The core JavaScript has the following requirements to build and test:
- Building a browser bundle:
- Node.js
- npm
- Testing
- Node.js
- npm
- Chrome, Firefox, Safari (optional)
Some special networking features can optionally use a Flash component. See the Flash README for details.
To create single file bundles for use with browsers run the following:
npm install
npm run build
This will create single non-minimized and minimized files that can be included in the browser:
dist/forge.js
dist/forge.min.js
A bundle that adds some utilities and networking support is also available:
dist/forge.all.js
dist/forge.all.min.js
Include the file via:
<script src="YOUR_SCRIPT_PATH/forge.js"></script>
or
<script src="YOUR_SCRIPT_PATH/forge.min.js"></script>
The above bundles will synchronously create a global 'forge' object.
Note: These bundles will not include any WebWorker scripts (eg:
dist/prime.worker.js
), so these will need to be accessible from the browser
if any WebWorkers are used.
The build process uses webpack and the config file can be modified to generate a file or files that only contain the parts of forge you need.
Browserify override support is also present in package.json
.
npm install
Forge natively runs in a Node.js environment:
npm test
Automated testing is done via Karma. By default it will run the tests with Headless Chrome.
npm run test-karma
Is 'mocha' reporter output too verbose? Other reporters are available. Try 'dots', 'progress', or 'tap'.
npm run test-karma -- --reporters progress
By default webpack is used. Browserify can also be used.
BUNDLER=browserify npm run test-karma
You can also specify one or more browsers to use.
npm run test-karma -- --browsers Chrome,Firefox,Safari,ChromeHeadless
The reporter option and BUNDLER
environment variable can also be used.
Testing in a browser uses webpack to combine forge and all tests and then
loading the result in a browser. A simple web server is provided that will
output the HTTP or HTTPS URLs to load. It also will start a simple Flash Policy
Server. Unit tests and older legacy tests are provided. Custom ports can be
used by running node tests/server.js
manually.
To run the unit tests in a browser a special forge build is required:
npm run test-build
To run legacy browser based tests the main forge build is required:
npm run build
The tests are run with a custom server that prints out the URLs to use:
npm run test-server
There are some other random tests and benchmarks available in the tests directory.
To perform coverage testing of the unit tests, run the following. The results
will be put in the coverage/
directory. Note that coverage testing can slow
down some tests considerably.
npm install
npm run coverage
Any contributions (eg: PRs) that are accepted will be brought under the same license used by the rest of the Forge project. This license allows Forge to be used under the terms of either the BSD License or the GNU General Public License (GPL) Version 2.
See: LICENSE
If a contribution contains 3rd party source code with its own license, it may retain it, so long as that license is compatible with the Forge license.
If at any time you wish to disable the use of native code, where available,
for particular forge features like its secure random number generator, you
may set the forge.options.usePureJavaScript
flag to true
. It is
not recommended that you set this flag as native code is typically more
performant and may have stronger security properties. It may be useful to
set this flag to test certain features that you plan to run in environments
that are different from your testing environment.
To disable native code when including forge in the browser:
// run this *after* including the forge script
forge.options.usePureJavaScript = true;
To disable native code when using Node.js:
var forge = require('node-forge');
forge.options.usePureJavaScript = true;
Provides a native javascript client and server-side TLS implementation.
Examples
// create TLS client
var client = forge.tls.createConnection({
server: false,
caStore: /* Array of PEM-formatted certs or a CA store object */,
sessionCache: {},
// supported cipher suites in order of preference
cipherSuites: [
forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA,
forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA],
virtualHost: 'example.com',
verify: function(connection, verified, depth, certs) {
if(depth === 0) {
var cn = certs[0].subject.getField('CN').value;
if(cn !== 'example.com') {
verified = {
alert: forge.tls.Alert.Description.bad_certificate,
message: 'Certificate common name does not match hostname.'
};
}
}
return verified;
},
connected: function(connection) {
console.log('connected');
// send message to server
connection.prepare(forge.util.encodeUtf8('Hi server!'));
/* NOTE: experimental, start heartbeat retransmission timer
myHeartbeatTimer = setInterval(function() {
connection.prepareHeartbeatRequest(forge.util.createBuffer('1234'));
}, 5*60*1000);*/
},
/* provide a client-side cert if you want
getCertificate: function(connection, hint) {
return myClientCertificate;
},
/* the private key for the client-side cert if provided */
getPrivateKey: function(connection, cert) {
return myClientPrivateKey;
},
tlsDataReady: function(connection) {
// TLS data (encrypted) is ready to be sent to the server
sendToServerSomehow(connection.tlsData.getBytes());
// if you were communicating with the server below, you'd do:
// server.process(connection.tlsData.getBytes());
},
dataReady: function(connection) {
// clear data from the server is ready
console.log('the server sent: ' +
forge.util.decodeUtf8(connection.data.getBytes()));
// close connection
connection.close();
},
/* NOTE: experimental
heartbeatReceived: function(connection, payload) {
// restart retransmission timer, look at payload
clearInterval(myHeartbeatTimer);
myHeartbeatTimer = setInterval(function() {
connection.prepareHeartbeatRequest(forge.util.createBuffer('1234'));
}, 5*60*1000);
payload.getBytes();
},*/
closed: function(connection) {
console.log('disconnected');
},
error: function(connection, error) {
console.log('uh oh', error);
}
});
// start the handshake process
client.handshake();
// when encrypted TLS data is received from the server, process it
client.process(encryptedBytesFromServer);
// create TLS server
var server = forge.tls.createConnection({
server: true,
caStore: /* Array of PEM-formatted certs or a CA store object */,
sessionCache: {},
// supported cipher suites in order of preference
cipherSuites: [
forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA,
forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA],
// require a client-side certificate if you want
verifyClient: true,
verify: function(connection, verified, depth, certs) {
if(depth === 0) {
var cn = certs[0].subject.getField('CN').value;
if(cn !== 'the-client') {
verified = {
alert: forge.tls.Alert.Description.bad_certificate,
message: 'Certificate common name does not match expected client.'
};
}
}
return verified;
},
connected: function(connection) {
console.log('connected');
// send message to client
connection.prepare(forge.util.encodeUtf8('Hi client!'));
/* NOTE: experimental, start heartbeat retransmission timer
myHeartbeatTimer = setInterval(function() {
connection.prepareHeartbeatRequest(forge.util.createBuffer('1234'));
}, 5*60*1000);*/
},
getCertificate: function(connection, hint) {
return myServerCertificate;
},
getPrivateKey: function(connection, cert) {
return myServerPrivateKey;
},
tlsDataReady: function(connection) {
// TLS data (encrypted) is ready to be sent to the client
sendToClientSomehow(connection.tlsData.getBytes());
// if you were communicating with the client above you'd do:
// client.process(connection.tlsData.getBytes());
},
dataReady: function(connection) {
// clear data from the client is ready
console.log('the client sent: ' +
forge.util.decodeUtf8(connection.data.getBytes()));
// close connection
connection.close();
},
/* NOTE: experimental
heartbeatReceived: function(connection, payload) {
// restart retransmission timer, look at payload
clearInterval(myHeartbeatTimer);
myHeartbeatTimer = setInterval(function() {
connection.prepareHeartbeatRequest(forge.util.createBuffer('1234'));
}, 5*60*1000);
payload.getBytes();
},*/
closed: function(connection) {
console.log('disconnected');
},
error: function(connection, error) {
console.log('uh oh', error);
}
});
// when encrypted TLS data is received from the client, process it
server.process(encryptedBytesFromClient);
Connect to a TLS server using node's net.Socket:
var socket = new net.Socket();
var client = forge.tls.createConnection({
server: false,
verify: function(connection, verified, depth, certs) {
// skip verification for testing
console.log('[tls] server certificate verified');
return true;
},
connected: function(connection) {
console.log('[tls] connected');
// prepare some data to send (note that the string is interpreted as
// 'binary' encoded, which works for HTTP which only uses ASCII, use
// forge.util.encodeUtf8(str) otherwise
client.prepare('GET / HTTP/1.0\r\n\r\n');
},
tlsDataReady: function(connection) {
// encrypted data is ready to be sent to the server
var data = connection.tlsData.getBytes();
socket.write(data, 'binary'); // encoding should be 'binary'
},
dataReady: function(connection) {
// clear data from the server is ready
var data = connection.data.getBytes();
console.log('[tls] data received from the server: ' + data);
},
closed: function() {
console.log('[tls] disconnected');
},
error: function(connection, error) {
console.log('[tls] error', error);
}
});
socket.on('connect', function() {
console.log('[socket] connected');
client.handshake();
});
socket.on('data', function(data) {
client.process(data.toString('binary')); // encoding should be 'binary'
});
socket.on('end', function() {
console.log('[socket] disconnected');
});
// connect to google.com
socket.connect(443, 'google.com');
// or connect to gmail's imap server (but don't send the HTTP header above)
//socket.connect(993, 'imap.gmail.com');
Provides a native JavaScript mini-implementation of an http client that uses pooled sockets.
Examples
// create an HTTP GET request
var request = forge.http.createRequest({method: 'GET', path: url.path});
// send the request somewhere
sendSomehow(request.toString());
// receive response
var buffer = forge.util.createBuffer();
var response = forge.http.createResponse();
var someAsyncDataHandler = function(bytes) {
if(!response.bodyReceived) {
buffer.putBytes(bytes);
if(!response.headerReceived) {
if(response.readHeader(buffer)) {
console.log('HTTP response header: ' + response.toString());
}
}
if(response.headerReceived && !response.bodyReceived) {
if(response.readBody(buffer)) {
console.log('HTTP response body: ' + response.body);
}
}
}
};
Provides some SSH utility functions.
Examples
// encodes (and optionally encrypts) a private RSA key as a Putty PPK file
forge.ssh.privateKeyToPutty(privateKey, passphrase, comment);
// encodes a public RSA key as an OpenSSH file
forge.ssh.publicKeyToOpenSSH(key, comment);
// encodes a private RSA key as an OpenSSH file
forge.ssh.privateKeyToOpenSSH(privateKey, passphrase);
// gets the SSH public key fingerprint in a byte buffer
forge.ssh.getPublicKeyFingerprint(key);
// gets a hex-encoded, colon-delimited SSH public key fingerprint
forge.ssh.getPublicKeyFingerprint(key, {encoding: 'hex', delimiter: ':'});
Provides an XmlHttpRequest implementation using forge.http as a backend.
Examples
// TODO
Provides an interface to create and use raw sockets provided via Flash.
Examples
// TODO
Provides a basic API for block encryption and decryption. There is built-in support for the ciphers: AES, 3DES, and DES, and for the modes of operation: ECB, CBC, CFB, OFB, CTR, and GCM.
These algorithms are currently supported:
- AES-ECB
- AES-CBC
- AES-CFB
- AES-OFB
- AES-CTR
- AES-GCM
- 3DES-ECB
- 3DES-CBC
- DES-ECB
- DES-CBC
When using an AES algorithm, the key size will determine whether AES-128, AES-192, or AES-256 is used (all are supported). When a DES algorithm is used, the key size will determine whether 3DES or regular DES is used. Use a 3DES algorithm to enforce Triple-DES.
Examples
// generate a random key and IV
// Note: a key size of 16 bytes will use AES-128, 24 => AES-192, 32 => AES-256
var key = forge.random.getBytesSync(16);
var iv = forge.random.getBytesSync(16);
/* alternatively, generate a password-based 16-byte key
var salt = forge.random.getBytesSync(128);
var key = forge.pkcs5.pbkdf2('password', salt, numIterations, 16);
*/
// encrypt some bytes using CBC mode
// (other modes include: ECB, CFB, OFB, CTR, and GCM)
// Note: CBC and ECB modes use PKCS#7 padding as default
var cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(someBytes));
cipher.finish();
var encrypted = cipher.output;
// outputs encrypted hex
console.log(encrypted.toHex());
// decrypt some bytes using CBC mode
// (other modes include: CFB, OFB, CTR, and GCM)
var decipher = forge.cipher.createDecipher('AES-CBC', key);
decipher.start({iv: iv});
decipher.update(encrypted);
var result = decipher.finish(); // check 'result' for true/false
// outputs decrypted hex
console.log(decipher.output.toHex());
// decrypt bytes using CBC mode and streaming
// Performance can suffer for large multi-MB inputs due to buffer
// manipulations. Stream processing in chunks can offer significant
// improvement. CPU intensive update() calls could also be performed with
// setImmediate/setTimeout to avoid blocking the main browser UI thread (not
// shown here). Optimal block size depends on the JavaScript VM and other
// factors. Encryption can use a simple technique for increased performance.
var encryptedBytes = encrypted.bytes();
var decipher = forge.cipher.createDecipher('AES-CBC', key);
decipher.start({iv: iv});
var length = encryptedBytes.length;
var chunkSize = 1024 * 64;
var index = 0;
var decrypted = '';
do {
decrypted += decipher.output.getBytes();
var buf = forge.util.createBuffer(encryptedBytes.substr(index, chunkSize));
decipher.update(buf);
index += chunkSize;
} while(index < length);
var result = decipher.finish();
assert(result);
decrypted += decipher.output.getBytes();
console.log(forge.util.bytesToHex(decrypted));
// encrypt some bytes using GCM mode
var cipher = forge.cipher.createCipher('AES-GCM', key);
cipher.start({
iv: iv, // should be a 12-byte binary-encoded string or byte buffer
additionalData: 'binary-encoded string', // optional
tagLength: 128 // optional, defaults to 128 bits
});
cipher.update(forge.util.createBuffer(someBytes));
cipher.finish();
var encrypted = cipher.output;
var tag = cipher.mode.tag;
// outputs encrypted hex
console.log(encrypted.toHex());
// outputs authentication tag
console.log(tag.toHex());
// decrypt some bytes using GCM mode
var decipher = forge.cipher.createDecipher('AES-GCM', key);
decipher.start({
iv: iv,
additionalData: 'binary-encoded string', // optional
tagLength: 128, // optional, defaults to 128 bits
tag: tag // authentication tag from encryption
});
decipher.update(encrypted);
var pass = decipher.finish();
// pass is false if there was a failure (eg: authentication tag didn't match)
if(pass) {
// outputs decrypted hex
console.log(decipher.output.toHex());
}
Using forge in Node.js to match openssl's "enc" command line tool (Note: OpenSSL "enc" uses a non-standard file format with a custom key derivation function and a fixed iteration count of 1, which some consider less secure than alternatives such as OpenPGP/GnuPG):
var forge = require('node-forge');
var fs = require('fs');
// openssl enc -des3 -in input.txt -out input.enc
function encrypt(password) {
var input = fs.readFileSync('input.txt', {encoding: 'binary'});
// 3DES key and IV sizes
var keySize = 24;
var ivSize = 8;
// get derived bytes
// Notes:
// 1. If using an alternative hash (eg: "-md sha1") pass
// "forge.md.sha1.create()" as the final parameter.
// 2. If using "-nosalt", set salt to null.
var salt = forge.random.getBytesSync(8);
// var md = forge.md.sha1.create(); // "-md sha1"
var derivedBytes = forge.pbe.opensslDeriveBytes(
password, salt, keySize + ivSize/*, md*/);
var buffer = forge.util.createBuffer(derivedBytes);
var key = buffer.getBytes(keySize);
var iv = buffer.getBytes(ivSize);
var cipher = forge.cipher.createCipher('3DES-CBC', key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(input, 'binary'));
cipher.finish();
var output = forge.util.createBuffer();
// if using a salt, prepend this to the output:
if(salt !== null) {
output.putBytes('Salted__'); // (add to match openssl tool output)
output.putBytes(salt);
}
output.putBuffer(cipher.output);
fs.writeFileSync('input.enc', output.getBytes(), {encoding: 'binary'});
}
// openssl enc -d -des3 -in input.enc -out input.dec.txt
function decrypt(password) {
var input = fs.readFileSync('input.enc', {encoding: 'binary'});
// parse salt from input
input = forge.util.createBuffer(input, 'binary');
// skip "Salted__" (if known to be present)
input.getBytes('Salted__'.length);
// read 8-byte salt
var salt = input.getBytes(8);
// Note: if using "-nosalt", skip above parsing and use
// var salt = null;
// 3DES key and IV sizes
var keySize = 24;
var ivSize = 8;
var derivedBytes = forge.pbe.opensslDeriveBytes(
password, salt, keySize + ivSize);
var buffer = forge.util.createBuffer(derivedBytes);
var key = buffer.getBytes(keySize);
var iv = buffer.getBytes(ivSize);
var decipher = forge.cipher.createDecipher('3DES-CBC', key);
decipher.start({iv: iv});
decipher.update(input);
var result = decipher.finish(); // check 'result' for true/false
fs.writeFileSync(
'input.dec.txt', decipher.output.getBytes(), {encoding: 'binary'});
}
Provides AES encryption and decryption in CBC, CFB, OFB, CTR, and GCM modes. See CIPHER for examples.
Provides 3DES and DES encryption and decryption in ECB and CBC modes. See CIPHER for examples.
Examples
// generate a random key and IV
var key = forge.random.getBytesSync(16);
var iv = forge.random.getBytesSync(8);
// encrypt some bytes
var cipher = forge.rc2.createEncryptionCipher(key);
cipher.start(iv);
cipher.update(forge.util.createBuffer(someBytes));
cipher.finish();
var encrypted = cipher.output;
// outputs encrypted hex
console.log(encrypted.toHex());
// decrypt some bytes
var cipher = forge.rc2.createDecryptionCipher(key);
cipher.start(iv);
cipher.update(encrypted);
cipher.finish();
// outputs decrypted hex
console.log(cipher.output.toHex());
Provides X.509 certificate support, ED25519 key generation and signing/verifying, and RSA public and private key encoding, decoding, encryption/decryption, and signing/verifying.
Special thanks to TweetNaCl.js for providing the bulk of the implementation.
Examples
var ed25519 = forge.pki.ed25519;
// generate a random ED25519 keypair
var keypair = ed25519.generateKeyPair();
// `keypair.publicKey` is a node.js Buffer or Uint8Array
// `keypair.privateKey` is a node.js Buffer or Uint8Array
// generate a random ED25519 keypair based on a random 32-byte seed
var seed = forge.random.getBytesSync(32);
var keypair = ed25519.generateKeyPair({seed: seed});
// generate a random ED25519 keypair based on a "password" 32-byte seed
var password = 'Mai9ohgh6ahxee0jutheew0pungoozil';
var seed = new forge.util.ByteBuffer(password, 'utf8');
var keypair = ed25519.generateKeyPair({seed: seed});
// sign a UTF-8 message
var signature = ED25519.sign({
message: 'test',
// also accepts `binary` if you want to pass a binary string
encoding: 'utf8',
// node.js Buffer, Uint8Array, forge ByteBuffer, binary string
privateKey: privateKey
});
// `signature` is a node.js Buffer or Uint8Array
// sign a message passed as a buffer
var signature = ED25519.sign({
// also accepts a forge ByteBuffer or Uint8Array
message: Buffer.from('test', 'utf8'),
privateKey: privateKey
});
// sign a message digest (shorter "message" == better performance)
var md = forge.md.sha256.create();
md.update('test', 'utf8');
var signature = ED25519.sign({
md: md,
privateKey: privateKey
});
// verify a signature on a UTF-8 message
var verified = ED25519.verify({
message: 'test',
encoding: 'utf8',
// node.js Buffer, Uint8Array, forge ByteBuffer, or binary string
signature: signature,
// node.js Buffer, Uint8Array, forge ByteBuffer, or binary string
publicKey: publicKey
});
// `verified` is true/false
// sign a message passed as a buffer
var verified = ED25519.verify({
// also accepts a forge ByteBuffer or Uint8Array
message: Buffer.from('test', 'utf8'),
// node.js Buffer, Uint8Array, forge ByteBuffer, or binary string
signature: signature,
// node.js Buffer, Uint8Array, forge ByteBuffer, or binary string
publicKey: publicKey
});
// verify a signature on a message digest
var md = forge.md.sha256.create();
md.update('test', 'utf8');
var verified = ED25519.verify({
md: md,
// node.js Buffer, Uint8Array, forge ByteBuffer, or binary string
signature: signature,
// node.js Buffer, Uint8Array, forge ByteBuffer, or binary string
publicKey: publicKey
});