mail/src/js/crypto/aes-cbc.js

81 lines
2.4 KiB
JavaScript
Raw Normal View History

2013-04-02 09:02:57 -04:00
/**
2013-05-14 06:49:27 -04:00
* A Wrapper for Forge's AES-CBC encryption with HMAC-SHA-256 an integrify check
2013-04-02 09:02:57 -04:00
*/
app.crypto.AesCBC = function() {
'use strict';
2013-03-13 11:58:46 -04:00
/**
2013-04-02 09:02:57 -04:00
* Encrypt a String using AES-CBC-Pkcs7 using the provided keysize (e.g. 128, 256)
2013-05-14 06:49:27 -04:00
* and create an HMAC-SHA-265 for integrity check
2013-04-02 09:02:57 -04:00
* @param plaintext [String] The input string in UTF8
* @param key [String] The base64 encoded key
* @param iv [String] The base64 encoded IV
* @return [String] The base64 encoded ciphertext
2013-03-13 11:58:46 -04:00
*/
2013-04-02 09:02:57 -04:00
this.encrypt = function(plaintext, key, iv) {
2013-05-14 06:49:27 -04:00
// parse base64 input to utf8
var keyUtf8 = forge.util.decode64(key);
var ivUtf8 = forge.util.decode64(iv);
// encrypt
var cipher = forge.aes.createEncryptionCipher(keyUtf8);
cipher.start(ivUtf8);
cipher.update(forge.util.createBuffer(plaintext));
cipher.finish();
var ctUtf8 = cipher.output.getBytes();
// get hmac
return {
hmac: this.getHmac(ctUtf8, keyUtf8, ivUtf8),
ciphertext: forge.util.encode64(ctUtf8)
};
2013-04-02 09:02:57 -04:00
};
2013-04-02 09:02:57 -04:00
/**
* Decrypt a String using AES-CBC-Pkcs7 using the provided keysize (e.g. 128, 256)
2013-05-14 06:49:27 -04:00
* and does an HMAC-SHA-265 integrity check
2013-04-02 09:02:57 -04:00
* @param ciphertext [String] The base64 encoded ciphertext
* @param key [String] The base64 encoded key
* @param iv [String] The base64 encoded IV
2013-05-14 06:49:27 -04:00
* @param iv [String] The base64 encoded HMAC
2013-04-02 09:02:57 -04:00
* @return [String] The decrypted plaintext in UTF8
*/
2013-05-14 06:49:27 -04:00
this.decrypt = function(ciphertext, key, iv, hmac) {
// parse base64 input to utf8
var ctUtf8 = forge.util.decode64(ciphertext);
var keyUtf8 = forge.util.decode64(key);
var ivUtf8 = forge.util.decode64(iv);
// check hmac
var checkedHmac = this.getHmac(ctUtf8, keyUtf8, ivUtf8);
if (hmac !== checkedHmac) {
throw new Error('The integrity check via HMAC failed!');
}
var cipher = forge.aes.createDecryptionCipher(keyUtf8);
cipher.start(ivUtf8);
cipher.update(forge.util.createBuffer(ctUtf8));
cipher.finish();
return cipher.output.getBytes();
};
/**
* Generate a base64 encoded HMAC using SHA-265
* @param input [String] The input string in UTF8
* @param key [String] The UTF8 encoded key
* @param iv [String] The UTF8 encoded IV
* @return [String] The base64 encoded hmac
*/
this.getHmac = function(input, key, iv) {
var hmac = forge.hmac.create();
hmac.start('sha256', key);
if (iv) {
hmac.update(iv);
}
hmac.update(input);
return forge.util.encode64(hmac.digest().getBytes());
2013-03-13 11:58:46 -04:00
};
2013-04-02 09:02:57 -04:00
};