Repository: Pakhee/Cross-platform-AES-encryption Branch: master Commit: 823f3ae081d2 Files: 18 Total size: 67.9 KB Directory structure: gitextract_ogl9ndbr/ ├── .gitignore ├── Android/ │ ├── CryptLib.java │ └── Usage.txt ├── C-Sharp/ │ ├── CryptLib.cs │ └── HowToUse.cs ├── LICENSE ├── Node/ │ ├── README.md │ ├── dist/ │ │ └── CryptLib.js │ ├── gulpfile.js │ ├── index.js │ ├── package.json │ ├── src/ │ │ └── CryptLib.js │ └── test/ │ └── CryptLib-test.js ├── README.md └── iOS/ ├── CryptLib.h ├── CryptLib.m ├── NSData+Base64.h └── NSData+Base64.m ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ Node/node_modules ================================================ FILE: Android/CryptLib.java ================================================ package com.pakhee.common; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.SecureRandom; import android.util.Base64; /***************************************************************** * CrossPlatform CryptLib * *

* This cross platform CryptLib uses AES 256 for encryption. This library can * be used for encryptoion and de-cryption of string on iOS, Android and Windows * platform.
* Features:
* 1. 256 bit AES encryption * 2. Random IV generation. * 3. Provision for SHA256 hashing of key. *

* * @since 1.0 * @author navneet *****************************************************************/ public class CryptLib { /** * Encryption mode enumeration */ private enum EncryptMode { ENCRYPT, DECRYPT; } // cipher to be used for encryption and decryption Cipher _cx; // encryption key and initialization vector byte[] _key, _iv; public CryptLib() throws NoSuchAlgorithmException, NoSuchPaddingException { // initialize the cipher with transformation AES/CBC/PKCS5Padding _cx = Cipher.getInstance("AES/CBC/PKCS5Padding"); _key = new byte[32]; //256 bit key space _iv = new byte[16]; //128 bit IV } /** * Note: This function is no longer used. * This function generates md5 hash of the input string * @param inputString * @return md5 hash of the input string */ public static final String md5(final String inputString) { final String MD5 = "MD5"; try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest .getInstance(MD5); digest.update(inputString.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuilder hexString = new StringBuilder(); for (byte aMessageDigest : messageDigest) { String h = Integer.toHexString(0xFF & aMessageDigest); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } /** * * @param _inputText * Text to be encrypted or decrypted * @param _encryptionKey * Encryption key to used for encryption / decryption * @param _mode * specify the mode encryption / decryption * @param _initVector * Initialization vector * @return encrypted or decrypted string based on the mode * @throws UnsupportedEncodingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws IllegalBlockSizeException * @throws BadPaddingException */ private String encryptDecrypt(String _inputText, String _encryptionKey, EncryptMode _mode, String _initVector) throws UnsupportedEncodingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String _out = "";// output string //_encryptionKey = md5(_encryptionKey); //System.out.println("key="+_encryptionKey); int len = _encryptionKey.getBytes("UTF-8").length; // length of the key provided if (_encryptionKey.getBytes("UTF-8").length > _key.length) len = _key.length; int ivlen = _initVector.getBytes("UTF-8").length; if(_initVector.getBytes("UTF-8").length > _iv.length) ivlen = _iv.length; System.arraycopy(_encryptionKey.getBytes("UTF-8"), 0, _key, 0, len); System.arraycopy(_initVector.getBytes("UTF-8"), 0, _iv, 0, ivlen); //KeyGenerator _keyGen = KeyGenerator.getInstance("AES"); //_keyGen.init(128); SecretKeySpec keySpec = new SecretKeySpec(_key, "AES"); // Create a new SecretKeySpec // for the // specified key // data and // algorithm // name. IvParameterSpec ivSpec = new IvParameterSpec(_iv); // Create a new // IvParameterSpec // instance with the // bytes from the // specified buffer // iv used as // initialization // vector. // encryption if (_mode.equals(EncryptMode.ENCRYPT)) { // Potentially insecure random numbers on Android 4.3 and older. // Read // https://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html // for more info. _cx.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);// Initialize this cipher instance byte[] results = _cx.doFinal(_inputText.getBytes("UTF-8")); // Finish // multi-part // transformation // (encryption) _out = Base64.encodeToString(results, Base64.DEFAULT); // ciphertext // output } // decryption if (_mode.equals(EncryptMode.DECRYPT)) { _cx.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);// Initialize this ipher instance byte[] decodedValue = Base64.decode(_inputText.getBytes(), Base64.DEFAULT); byte[] decryptedVal = _cx.doFinal(decodedValue); // Finish // multi-part // transformation // (decryption) _out = new String(decryptedVal); } System.out.println(_out); return _out; // return encrypted/decrypted string } /*** * This function computes the SHA256 hash of input string * @param text input text whose SHA256 hash has to be computed * @param length length of the text to be returned * @return returns SHA256 hash of input text * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ public static String SHA256 (String text, int length) throws NoSuchAlgorithmException, UnsupportedEncodingException { String resultStr; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes("UTF-8")); byte[] digest = md.digest(); StringBuffer result = new StringBuffer(); for (byte b : digest) { result.append(String.format("%02x", b)); //convert to hex } //return result.toString(); if(length > result.toString().length()) { resultStr = result.toString(); } else { resultStr = result.toString().substring(0, length); } return resultStr; } /*** * This function encrypts the plain text to cipher text using the key * provided. You'll have to use the same key for decryption * * @param _plainText * Plain text to be encrypted * @param _key * Encryption Key. You'll have to use the same key for decryption * @param _iv * initialization Vector * @return returns encrypted (cipher) text * @throws InvalidKeyException * @throws UnsupportedEncodingException * @throws InvalidAlgorithmParameterException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public String encrypt(String _plainText, String _key, String _iv) throws InvalidKeyException, UnsupportedEncodingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { return encryptDecrypt(_plainText, _key, EncryptMode.ENCRYPT, _iv); } /*** * This funtion decrypts the encrypted text to plain text using the key * provided. You'll have to use the same key which you used during * encryprtion * * @param _encryptedText * Encrypted/Cipher text to be decrypted * @param _key * Encryption key which you used during encryption * @param _iv * initialization Vector * @return encrypted value * @throws InvalidKeyException * @throws UnsupportedEncodingException * @throws InvalidAlgorithmParameterException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public String decrypt(String _encryptedText, String _key, String _iv) throws InvalidKeyException, UnsupportedEncodingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { return encryptDecrypt(_encryptedText, _key, EncryptMode.DECRYPT, _iv); } /** * this function generates random string for given length * @param length * Desired length * * @return */ public static String generateRandomIV(int length) { SecureRandom ranGen = new SecureRandom(); byte[] aesKey = new byte[16]; ranGen.nextBytes(aesKey); StringBuffer result = new StringBuffer(); for (byte b : aesKey) { result.append(String.format("%02x", b)); //convert to hex } if(length> result.toString().length()) { return result.toString(); } else { return result.toString().substring(0, length); } } } ================================================ FILE: Android/Usage.txt ================================================ //This is how to use CryptLib.java try { CryptLib _crypt = new CryptLib(); String output= ""; String plainText = "This is the text to be encrypted."; String key = CryptLib.SHA256("my secret key", 32); //32 bytes = 256 bit String iv = CryptLib.generateRandomIV(16); //16 bytes = 128 bit output = _crypt.encrypt(plainText, key, iv); //encrypt System.out.println("encrypted text=" + output); output = _crypt.decrypt(output, key,iv); //decrypt System.out.println("decrypted text=" + output); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } If you are getting "java.security.InvalidKeyException: Illegal key size" error while compiling, see this - http://stackoverflow.com/questions/6481627/java-security-illegal-key-size-or-default-parameters ================================================ FILE: C-Sharp/CryptLib.cs ================================================ using System; using System.Text; using System.Security.Cryptography; namespace com.pakhee.common { /***************************************************************** * CrossPlatform CryptLib * *

* This cross platform CryptLib uses AES 256 for encryption. This library can * be used for encryptoion and de-cryption of string on iOS, Android and Windows * platform.
* Features:
* 1. 256 bit AES encryption * 2. Random IV generation. * 3. Provision for SHA256 hashing of key. *

* * @since 1.0 * @author navneet *****************************************************************/ public class CryptLib { UTF8Encoding _enc; RijndaelManaged _rcipher; byte[] _key, _pwd, _ivBytes, _iv; /*** * Encryption mode enumeration */ private enum EncryptMode {ENCRYPT, DECRYPT}; static readonly char[] CharacterMatrixForRandomIVStringGeneration = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' }; /** * This function generates random string of the given input length. * * @param _plainText * Plain text to be encrypted * @param _key * Encryption Key. You'll have to use the same key for decryption * @return returns encrypted (cipher) text */ internal static string GenerateRandomIV(int length) { char[] _iv = new char[length]; byte[] randomBytes = new byte[length]; using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) { rng.GetBytes(randomBytes); //Fills an array of bytes with a cryptographically strong sequence of random values. } for (int i = 0; i < _iv.Length; i++) { int ptr = randomBytes[i] % CharacterMatrixForRandomIVStringGeneration.Length; _iv[i] = CharacterMatrixForRandomIVStringGeneration[ptr]; } return new string(_iv); } public CryptLib() { _enc = new UTF8Encoding(); _rcipher = new RijndaelManaged(); _rcipher.Mode = CipherMode.CBC; _rcipher.Padding = PaddingMode.PKCS7; _rcipher.KeySize = 256; _rcipher.BlockSize = 128; _key = new byte[32]; _iv = new byte[_rcipher.BlockSize/8]; //128 bit / 8 = 16 bytes _ivBytes = new byte[16]; } /** * * @param _inputText * Text to be encrypted or decrypted * @param _encryptionKey * Encryption key to used for encryption / decryption * @param _mode * specify the mode encryption / decryption * @param _initVector * initialization vector * @return encrypted or decrypted string based on the mode */ private String encryptDecrypt (string _inputText, string _encryptionKey, EncryptMode _mode, string _initVector) { string _out = "";// output string //_encryptionKey = MD5Hash (_encryptionKey); _pwd = Encoding.UTF8.GetBytes(_encryptionKey); _ivBytes = Encoding.UTF8.GetBytes (_initVector); int len = _pwd.Length; if (len > _key.Length) { len = _key.Length; } int ivLenth = _ivBytes.Length; if (ivLenth > _iv.Length) { ivLenth = _iv.Length; } Array.Copy(_pwd, _key, len); Array.Copy (_ivBytes, _iv, ivLenth); _rcipher.Key = _key; _rcipher.IV = _iv; if (_mode.Equals (EncryptMode.ENCRYPT)) { //encrypt byte[] plainText = _rcipher.CreateEncryptor().TransformFinalBlock(_enc.GetBytes(_inputText) , 0, _inputText.Length); _out = Convert.ToBase64String(plainText); } if (_mode.Equals (EncryptMode.DECRYPT)) { //decrypt byte[] plainText = _rcipher.CreateDecryptor().TransformFinalBlock(Convert.FromBase64String(_inputText), 0, Convert.FromBase64String(_inputText).Length); _out = _enc.GetString(plainText); } _rcipher.Dispose(); return _out;// return encrypted/decrypted string } /** * This function encrypts the plain text to cipher text using the key * provided. You'll have to use the same key for decryption * * @param _plainText * Plain text to be encrypted * @param _key * Encryption Key. You'll have to use the same key for decryption * @return returns encrypted (cipher) text */ public string encrypt (string _plainText, string _key, string _initVector) { return encryptDecrypt(_plainText, _key, EncryptMode.ENCRYPT, _initVector); } /*** * This funtion decrypts the encrypted text to plain text using the key * provided. You'll have to use the same key which you used during * encryprtion * * @param _encryptedText * Encrypted/Cipher text to be decrypted * @param _key * Encryption key which you used during encryption * @return encrypted value */ public string decrypt(string _encryptedText, string _key, string _initVector) { return encryptDecrypt(_encryptedText, _key, EncryptMode.DECRYPT, _initVector); } /*** * This function decrypts the encrypted text to plain text using the key * provided. You'll have to use the same key which you used during * encryption * * @param _encryptedText * Encrypted/Cipher text to be decrypted * @param _key * Encryption key which you used during encryption */ public static string getHashSha256(string text, int length) { byte[] bytes = Encoding.UTF8.GetBytes(text); SHA256Managed hashstring = new SHA256Managed(); byte[] hash = hashstring.ComputeHash(bytes); string hashString = string.Empty; foreach (byte x in hash) { hashString += String.Format("{0:x2}", x); //covert to hex string } if (length > hashString.Length) return hashString; else return hashString.Substring (0, length); } //this function is no longer used. private static string MD5Hash(string text) { MD5 md5 = new MD5CryptoServiceProvider(); //compute hash from the bytes of text md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text)); //get hash result after compute it byte[] result = md5.Hash; StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < result.Length; i++) { //change it into 2 hexadecimal digits //for each byte strBuilder.Append(result[i].ToString("x2")); } Console.WriteLine ("md5 hash of they key=" + strBuilder.ToString ()); return strBuilder.ToString(); } } } ================================================ FILE: C-Sharp/HowToUse.cs ================================================ public class test { public static void Main (String []args) { CryptLib _crypt = new CryptLib (); string plainText = "This is the text to be encrypted"; String iv = CryptLib.GenerateRandomIV (16); //16 bytes = 128 bits string key = CryptLib.getHashSha256("my secret key", 31); //32 bytes = 256 bits String cypherText = _crypt.encrypt (plainText, key, iv); Console.WriteLine ("iv="+iv); Console.WriteLine ("key=" + key); Console.WriteLine("Cypher text=" + cypherText); Console.WriteLine ("Plain text =" + _crypt.decrypt (cypherText, key, iv)); } } ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015 NAVNEET KUMAR Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: Node/README.md ================================================ CryptLib ========= A module to encrypt/decrypt string in Node, written in ES6 (src folder) and transpiled using Babel to ES5(dist folder). Using companion framework libraries, you should be able to encrypt/decrypt between node, iOS, Android and Windows platforms. Companion libs can be found here: https://github.com/Pakhee/Cross-platform-AES-encryption ## Installation npm install cryptlib --save ## Usage var CryptLib = require('cryptlib'), _crypt = new CryptLib(), plainText = 'This is the text to be encrypted', iv = _crypt.generateRandomIV(16), //16 bytes = 128 bit key = _crypt.getHashSha256('my secret key', 32), //32 bytes = 256 bits cypherText = _crypt.encrypt(plainText, key, iv), originalText = _crypt.decrypt(cypherText, key, iv); ## Run Code Sample npm start ## Tests npm test ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code. ## Release History * 0.1.0 Initial release ## License Apache License; see [LICENSE](../LICENSE). (c) 2015 by Abdul Khan ================================================ FILE: Node/dist/CryptLib.js ================================================ /*global console*/ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto); var _bl = require('bl'); var _bl2 = _interopRequireDefault(_bl); var _lodashIsarray = require('lodash.isarray'); var _lodashIsarray2 = _interopRequireDefault(_lodashIsarray); /** * CrossPlatform CryptLib * This cross platform CryptLib uses AES 256 for encryption. This library can * be used for encryption and de-cryption of strings on iOS, Android, Windows * and Node platform. * Features: * 1. 256 bit AES encryption * 2. Random IV generation. * 3. Provision for SHA256 hashing of key. */ var CryptLib = (function () { function CryptLib() { _classCallCheck(this, CryptLib); this._maxKeySize = 32; this._maxIVSize = 16; this._algorithm = 'AES-256-CBC'; this._characterMatrixForRandomIVStringGeneration = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_']; } _createClass(CryptLib, [{ key: '_encryptDecrypt', /** * private function: _encryptDecrypt * encryptes or decrypts to or from text or encrypted text given an iv and key * @param {string} text can be plain text or encrypted text * @param {string} key the key used to encrypt or decrypt * @param {string} initVector the initialization vector to encrypt or * decrypt * @param {bool} isEncrypt true = encryption, false = decryption * @return {string} encryted text or plain text */ value: function _encryptDecrypt(text, key, initVector, isEncrypt) { if (!text || !key) { throw 'cryptLib._encryptDecrypt: -> key and plain or encrypted text ' + 'required'; } var ivBl = new _bl2['default'](), keyBl = new _bl2['default'](), keyCharArray = key.split(''), ivCharArray = [], encryptor = undefined, decryptor = undefined, clearText = undefined; if (initVector && initVector.length > 0) { ivCharArray = initVector.split(''); } for (var i = 0; i < this._maxIVSize; i++) { ivBl.append(ivCharArray.shift() || [null]); } for (var i = 0; i < this._maxKeySize; i++) { keyBl.append(keyCharArray.shift() || [null]); } if (isEncrypt) { encryptor = _crypto2['default'].createCipheriv(this._algorithm, keyBl.toString(), ivBl.toString()); encryptor.setEncoding('base64'); encryptor.write(text); encryptor.end(); return encryptor.read(); } decryptor = _crypto2['default'].createDecipheriv(this._algorithm, keyBl.toString(), ivBl.toString()); var dec = decryptor.update(text, 'base64', 'utf8'); dec += decryptor.final('utf8'); return dec; } }, { key: '_isCorrectLength', /** * private function: _isCorrectLength * checks if length is preset and is a whole number and > 0 * @param {int} length * @return {bool} */ value: function _isCorrectLength(length) { return length && /^\d+$/.test(length) && parseInt(length, 10) !== 0; } }, { key: 'generateRandomIV', /** * generates random initaliztion vector given a length * @param {int} length the length of the iv to be generated */ value: function generateRandomIV(length) { if (!this._isCorrectLength(length)) { throw 'cryptLib.generateRandomIV() -> needs length or in wrong format'; } length = parseInt(length, 10); var _iv = [], randomBytes = _crypto2['default'].randomBytes(length); for (var i = 0; i < length; i++) { var ptr = randomBytes[i] % this._characterMatrixForRandomIVStringGeneration.length; _iv[i] = this._characterMatrixForRandomIVStringGeneration[ptr]; } return _iv.join(''); } }, { key: 'getHashSha256', /** * Creates a hash of a key using SHA-256 algorithm * @param {string} key the key that will be hashed * @param {int} length the length of the SHA-256 hash * @return {string} the output hash generated given a key and length */ value: function getHashSha256(key, length) { if (!key) { throw 'cryptLib.getHashSha256() -> needs key'; } if (!this._isCorrectLength(length)) { throw 'cryptLib.getHashSha256() -> needs length or in wrong format'; } return _crypto2['default'].createHash('sha256').update(key).digest('hex').substring(0, length); } }, { key: 'encrypt', /** * encryptes plain text given a key and initialization vector * @param {string} text can be plain text or encrypted text * @param {string} key the key used to encrypt or decrypt * @param {string} initVector the initialization vector to encrypt or * decrypt * @return {string} encryted text or plain text */ value: function encrypt(plainText, key, initVector) { return this._encryptDecrypt(plainText, key, initVector, true); } }, { key: 'decrypt', /** * decrypts encrypted text given a key and initialization vector * @param {string} text can be plain text or encrypted text * @param {string} key the key used to encrypt or decrypt * @param {string} initVector the initialization vector to encrypt or * decrypt * @return {string} encryted text or plain text */ value: function decrypt(encryptedText, key, initVector) { return this._encryptDecrypt(encryptedText, key, initVector, false); } }]); return CryptLib; })(); exports['default'] = CryptLib; module.exports = exports['default']; ================================================ FILE: Node/gulpfile.js ================================================ var gulp = require('gulp'); var babel = require('gulp-babel'); var mocha = require('gulp-mocha'); gulp.task('babel', function() { return gulp.src('src/*.js') .pipe(babel()) .pipe(gulp.dest('dist/')); }); gulp.task('watch', function() { gulp.watch('src/*.js', ['babel']); }); gulp.task('test', ['babel'], function() { return gulp.src(['test/*.js']) .pipe(mocha({ reporter: 'spec' })) .on('error', function(err) { console.log(err.stack); }); }); // Default Task gulp.task('default', ['babel', 'test']); ================================================ FILE: Node/index.js ================================================ /*global require*/ var CryptLib = require('cryptlib'), _crypt = new CryptLib(), plainText = 'This is the text to be encrypted', iv = _crypt.generateRandomIV(16), //16 bytes = 128 bit key = _crypt.getHashSha256('my secret key', 32), //32 bytes = 256 bits cypherText = _crypt.encrypt(plainText, key, iv); console.log('iv = %s', iv); console.log('key = %s', key); console.log('Cypher text = %s', cypherText); console.log('Plain text = %s', _crypt.decrypt(cypherText, key, iv)); ================================================ FILE: Node/package.json ================================================ { "name": "cryptlib", "version": "1.0.0", "author": { "name": "Abdul Khan" }, "main": "dist/CryptLib.js", "description": "CryptLib uses AES 256 for encryption or decryption. This library can be used for encryption and decryption of strings using Node on iOS, Android and Windows", "contributors": [ { "name": "Abdul Khan", "email": "invalidred@gmail.com" }, { "name": "Alexey Novak", "email": "alexey.novak.mail@gmail.com" } ], "scripts": { "start": "node index.js", "test": "node node_modules/mocha/bin/mocha --reporter spec test/*" }, "repository": { "type": "git", "url": "git+ssh://git@github.com:invalidred/Cross-platform-AES-encryption.git" }, "keywords": [ "AES node", "Cross Platform", "Encryption", "Decryption" ], "dependencies": { "bl": "4.0.3", "lodash.isarray": "3.0.4", "lodash.isfunction": "3.0.6" }, "devDependencies": { "babel": "^5.2.17", "chai": "^2.3.0", "gulp": "^3.8.11", "gulp-babel": "^5.1.0", "gulp-mocha": "^2.0.1", "mocha": "^2.2.4" }, "engine": "node >= 0.10.x", "homepage": "https://github.com/invalidred/Cross-platform-AES-encryption", "bugs": { "url": "https://github.com/Pakhee/Cross-platform-AES-encryption/issues" }, "private": false, "license": "Apache", "_npmVersion": "2.5.1", "_nodeVersion": "0.12.0", "_npmUser": { "name": "invalidred", "email": "invalidred@gmail.com" }, "maintainers": [ { "name": "Abdul Khan", "email": "invalidred@gmail.com" } ] } ================================================ FILE: Node/src/CryptLib.js ================================================ /*global console*/ 'use strict'; import crypto from 'crypto'; import BufferList from 'bl'; import isArray from 'lodash.isarray'; /** * CrossPlatform CryptLib * This cross platform CryptLib uses AES 256 for encryption. This library can * be used for encryption and de-cryption of strings on iOS, Android, Windows * and Node platform. * Features: * 1. 256 bit AES encryption * 2. Random IV generation. * 3. Provision for SHA256 hashing of key. */ export default class CryptLib { constructor() { this._maxKeySize = 32; this._maxIVSize = 16; this._algorithm = 'AES-256-CBC'; this._characterMatrixForRandomIVStringGeneration = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' ]; } /** * private function: _encryptDecrypt * encryptes or decrypts to or from text or encrypted text given an iv and key * @param {string} text can be plain text or encrypted text * @param {string} key the key used to encrypt or decrypt * @param {string} initVector the initialization vector to encrypt or * decrypt * @param {bool} isEncrypt true = encryption, false = decryption * @return {string} encryted text or plain text */ _encryptDecrypt(text, key, initVector, isEncrypt) { if (!text || !key) { throw 'cryptLib._encryptDecrypt: -> key and plain or encrypted text '+ 'required'; } let ivBl = new BufferList(), keyBl = new BufferList(), keyCharArray = key.split(''), ivCharArray = [], encryptor, decryptor, clearText; if (initVector && initVector.length > 0) { ivCharArray = initVector.split(''); } for (var i = 0; i < this._maxIVSize; i++) { ivBl.append(ivCharArray.shift() || [null]); } for (var i = 0; i < this._maxKeySize; i++) { keyBl.append(keyCharArray.shift() || [null]); } if (isEncrypt) { encryptor = crypto.createCipheriv(this._algorithm, keyBl.toString(), ivBl.toString()); encryptor.setEncoding('base64'); encryptor.write(text); encryptor.end(); return encryptor.read(); } decryptor = crypto.createDecipheriv(this._algorithm, keyBl.toString(), ivBl.toString()); var dec = decryptor.update(text, 'base64', 'utf8'); dec += decryptor.final('utf8'); return dec; } /** * private function: _isCorrectLength * checks if length is preset and is a whole number and > 0 * @param {int} length * @return {bool} */ _isCorrectLength(length) { return length && /^\d+$/.test(length) && parseInt(length, 10) !== 0 } /** * generates random initaliztion vector given a length * @param {int} length the length of the iv to be generated */ generateRandomIV(length) { if (!this._isCorrectLength(length)) { throw 'cryptLib.generateRandomIV() -> needs length or in wrong format'; } length = parseInt(length, 10); let _iv = [], randomBytes = crypto.randomBytes(length); for (let i = 0; i < length; i++) { let ptr = randomBytes[i] % this._characterMatrixForRandomIVStringGeneration.length; _iv[i] = this._characterMatrixForRandomIVStringGeneration[ptr]; } return _iv.join(''); } /** * Creates a hash of a key using SHA-256 algorithm * @param {string} key the key that will be hashed * @param {int} length the length of the SHA-256 hash * @return {string} the output hash generated given a key and length */ getHashSha256(key, length) { if (!key) { throw 'cryptLib.getHashSha256() -> needs key'; } if (!this._isCorrectLength(length)) { throw 'cryptLib.getHashSha256() -> needs length or in wrong format'; } return crypto.createHash('sha256') .update(key) .digest('hex') .substring(0, length); } /** * encryptes plain text given a key and initialization vector * @param {string} text can be plain text or encrypted text * @param {string} key the key used to encrypt or decrypt * @param {string} initVector the initialization vector to encrypt or * decrypt * @return {string} encryted text or plain text */ encrypt(plainText, key, initVector) { return this._encryptDecrypt(plainText, key, initVector, true); } /** * decrypts encrypted text given a key and initialization vector * @param {string} text can be plain text or encrypted text * @param {string} key the key used to encrypt or decrypt * @param {string} initVector the initialization vector to encrypt or * decrypt * @return {string} encryted text or plain text */ decrypt(encryptedText, key, initVector) { return this._encryptDecrypt(encryptedText, key, initVector, false); } } ================================================ FILE: Node/test/CryptLib-test.js ================================================ /*global it, describe, require*/ var chai = require('chai'), expect = chai.expect, CryptLib = require('../dist/cryptLib.js'); describe('CryptLib', function() { var cryptLib; before(function() { cryptLib = new CryptLib(); }); after(function() { cryptLib = null; }); describe('generateRandomIV()', function() { var errorMessage = 'cryptLib.generateRandomIV() -> needs length or in wrong format'; it('no length should throw error', function() { try { cryptLib.generateRandomIV() } catch (message) { expect(message).to.equal(errorMessage); } }); it('non-numeric and non-whole number length should throw error', function() { try{ cryptLib.generateRandomIV('abc'); } catch (message) { expect(message).to.equal(errorMessage); } try{ cryptLib.generateRandomIV('12a'); } catch (message) { expect(message).to.equal(errorMessage); } try{ cryptLib.generateRandomIV('12.2'); } catch (message) { expect(message).to.equal(errorMessage); } }); it('negative length should throw error', function() { try { cryptLib.generateRandomIV('-1'); } catch (message) { expect(message).to.equal(errorMessage); } }); it('length = 0, should throw error', function() { try { cryptLib.generateRandomIV(0); } catch (message) { expect(message).to.equal(errorMessage); } try { cryptLib.generateRandomIV('0'); } catch (message) { expect(message).to.equal(errorMessage); } }); it('length = 2', function() { var iv = cryptLib.generateRandomIV(2); expect(iv).to.have.length(2); expect(iv).to.be.string; }); it('length = 100', function() { var iv = cryptLib.generateRandomIV(100); expect(iv).to.have.length(100); expect(iv).to.be.string; }); }); describe('getHashSha256()', function() { var lengthErrorMessage = 'cryptLib.getHashSha256() -> needs length or in wrong format', keyErrorMessage = 'cryptLib.getHashSha256() -> needs key', validKey = 'key'; it('no key should throw error', function() { try { cryptLib.getHashSha256(null,2); } catch (message) { expect(message).to.equal(keyErrorMessage); } }); it('no length should throw error', function() { try { cryptLib.getHashSha256(validKey, null); } catch (message) { expect(message).to.equal(lengthErrorMessage); } }); it('non-numeric and non-whole number length should throw error', function() { try{ cryptLib.getHashSha256(validKey, 'abc'); } catch (message) { expect(message).to.equal(lengthErrorMessage); } try{ cryptLib.getHashSha256(validKey, '12a'); } catch (message) { expect(message).to.equal(lengthErrorMessage); } try{ cryptLib.getHashSha256(validKey, '12.2'); } catch (message) { expect(message).to.equal(lengthErrorMessage); } }); it('negative length should throw error', function() { try { cryptLib.getHashSha256(validKey, '-1'); } catch (message) { expect(message).to.equal(lengthErrorMessage); } try { cryptLib.getHashSha256(validKey, -1); } catch (message) { expect(message).to.equal(lengthErrorMessage); } }); it('length = 0, should throw error', function() { try { cryptLib.getHashSha256(validKey, 0); } catch (message) { expect(message).to.equal(lengthErrorMessage); } try { cryptLib.getHashSha256(validKey, '0'); } catch (message) { expect(message).to.equal(lengthErrorMessage); } }); it('valid key with length = 2', function() { var sha = cryptLib.getHashSha256(validKey, 2); expect(sha).to.have.length(2); expect(sha).to.be.string; }); it('valid key with length = 64', function() { var sha = cryptLib.getHashSha256(validKey, 64); expect(sha).to.have.length(64); expect(sha).to.be.string; }); it('valid key with length = 100 should return 64 char sha', function() { var sha = cryptLib.getHashSha256(validKey, 100); expect(sha).to.have.length(64); expect(sha).to.be.string; }); }); describe('encrypt() and decrypt() tests', function() { var errorMessage = 'cryptLib._encryptDecrypt: -> key and plain or encrypted text required', plainText = 'This is the plain text that will be encrypted and decrypted', myKey = 'myKey'; it('encrypt() with no plain text should throw error', function() { try { cryptLib.encrypt(null, 'key123', 'iv123'); } catch(error) { expect(error).to.equal(errorMessage); } }); it('encrypt() with no key should throw error', function() { try { cryptLib.encrypt(plainText, null, 'iv123'); } catch(error) { expect(error).to.equal(errorMessage); } }); it('basic encrypt() decrypt() locally : 0 char iv and 2 char key', function() { var iv = '', keyHashed = cryptLib.getHashSha256(myKey, 2), encryptedText = cryptLib.encrypt(plainText, keyHashed, iv), regularText = cryptLib.decrypt(encryptedText, keyHashed, iv); expect(regularText).to.equal(plainText); }); it('basic encrypt() decrypt() locally : 2 char iv and 2 char key', function() { var iv = cryptLib.generateRandomIV(2), keyHashed = cryptLib.getHashSha256(myKey, 2), encryptedText = cryptLib.encrypt(plainText, keyHashed, iv), decryptedText = cryptLib.decrypt(encryptedText, keyHashed, iv); expect(decryptedText).to.equal(plainText); }); it('basic encrypt() decrypt() locally : 16 char iv and 32 char key', function() { var iv = cryptLib.generateRandomIV(16), keyHashed = cryptLib.getHashSha256(myKey, 32), encryptedText = cryptLib.encrypt(plainText, keyHashed, iv), decryptedText = cryptLib.decrypt(encryptedText, keyHashed, iv); expect(decryptedText).to.equal(plainText); }); it('basic encrypt() decrypt() locally : 20 char iv and 80 char key', function() { var iv = cryptLib.generateRandomIV(20), keyHashed = cryptLib.getHashSha256(myKey, 80), encryptedText = cryptLib.encrypt(plainText, keyHashed, iv), decryptedText = cryptLib.decrypt(encryptedText, keyHashed, iv); expect(decryptedText).to.equal(plainText); }); it('decrypt 0 char iv and 2 char key generated by c#', function() { var cSharpIv = '', cSharpKey = 'b1', cSharpPlainText = 'C# text that\'s going to be decrypted', cSharpCipher = 'M2rfrn9DqNHJe3Hev9nMxKKgIHoqUsc7FJM+tBGxIrl3Wk9UeKIQ5fRUUZF3q2i5', nodeDecrpytedText; nodeDecrpytedText = cryptLib.decrypt(cSharpCipher, cSharpKey, cSharpIv); expect(nodeDecrpytedText).to.equal(cSharpPlainText); }); it('decrypt 2 char iv and 2 char key generated by c#', function() { var cSharpIv = 'sA', cSharpKey = 'b1', cSharpPlainText = 'C# text that\'s going to be decrypted', cSharpCipher = '90iAiA80rSiyEoCAnLC9KNYt41koQKs2Lo5NzciyELkoZGne+BAv1ScMXSWETyAL', nodeDecrpytedText; nodeDecrpytedText = cryptLib.decrypt(cSharpCipher, cSharpKey, cSharpIv); expect(nodeDecrpytedText).to.equal(cSharpPlainText); }); it('decrypt 16 char iv and 32 char key generated by c#', function() { var cSharpIv = 'HCHXjb_wIURjCV3G', cSharpKey = 'b16920894899c7780b5fc7161560a412', cSharpPlainText = 'C# text that\'s going to be decrypted', cSharpCipher = '0kv/H19UoAN21Et5jSNTM/yKQAaEPiB5Y6qugTQs3kvNuwMLBiOeFwMFnYr9KZBa', nodeDecrpytedText; nodeDecrpytedText = cryptLib.decrypt(cSharpCipher, cSharpKey, cSharpIv); expect(nodeDecrpytedText).to.equal(cSharpPlainText); }); }); }); ================================================ FILE: README.md ================================================ Cross platform 256bit AES encryption / decryption. ======== This project contains the implementation of 256 bit AES encryption which works on all the platforms (C#, iOS, Android and Node.js). One of the key objective is to make AES work on all the platforms with simple implementation. Platforms Supported: 1. iOS 2. Android 3. Windows (C#). 4. Node.js Features: 1. Cross platform support. Encryption-Decryption works across C#, iOS, Android and Node.js. 2. Support for Random IV (initialization vector) for encryption and decryption. Randomization is crucial for encryption schemes to achieve semantic security, a property whereby repeated usage of the scheme under the same key does not allow an attacker to infer relationships between segments of the encrypted message. 3. Support for SHA-256 for hashing the key. Never use plain text as encryption key. Always hash the plain text key and then use for encryption. AES permits the use of 256-bit keys. Breaking a symmetric 256-bit key by brute force requires 2^128 times more computational power than a 128-bit key. A device that could check a billion billion (10^18) AES keys per second would in theory require about 3×10^51 years to exhaust the 256-bit key space. How to encrypt a string: See code samples for more details. You'll have to perform following steps: 1. Generate Ramdom IV using the provided randomIV generator function. 2. Select a secret key and hash it using the provided SHA-256 hash function. 3. Encrypt your string using the hashed key and random IV. How to decrypt a string: See code samples for more details. You'll have to perform following steps: 1. Get the encrypted text and the randomIV used for encryption 2. Decrypt the string using the provided decrypt function ! ================================================ FILE: iOS/CryptLib.h ================================================ // // CryptLib.h // #import #import @interface StringEncryption : NSObject - (NSData *)encrypt:(NSData *)plainText key:(NSString *)key iv:(NSString *)iv; - (NSData *)decrypt:(NSData *)encryptedText key:(NSString *)key iv:(NSString *)iv; - (NSData *)generateRandomIV:(size_t)length; - (NSString *) md5:(NSString *) input; - (NSString*) sha256:(NSString *)key length:(NSInteger) length; @end ================================================ FILE: iOS/CryptLib.m ================================================ /***************************************************************** * CrossPlatform CryptLib * *

* This cross platform CryptLib uses AES 256 for encryption. This library can * be used for encryptoion and de-cryption of string on iOS, Android and Windows * platform.
* Features:
* 1. 256 bit AES encryption * 2. Random IV generation. * 3. Provision for SHA256 hashing of key. *

* * @since 1.0 * @author navneet *****************************************************************/ // How to use : // // 1. Encryption: // NSString * _secret = @"This the sample text has to be encrypted"; // this is the text that you want to encrypt. // NSString * _key = @"shared secret"; //secret key for encryption. To make encryption stronger, we will not use this key directly. We'll first hash the key next step and then use it. // key = [[StringEncryption alloc] sha256:key length:32]; //this is very important, 32 bytes = 256 bit // NSString * iv = [[[[StringEncryption alloc] generateRandomIV:11] base64EncodingWithLineLength:0] substringToIndex:16]; //Here we are generating random initialization vector (iv). Length of this vector = 16 bytes = 128 bits // Now that we have input text, hashed key and random IV, we are all set for encryption: // NSData * encryptedData = [[StringEncryption alloc] encrypt:[secret dataUsingEncoding:NSUTF8StringEncoding] key:key iv:iv]; // NSLog(@"encrypted data:: %@", [encryptedData base64EncodingWithLineLength:0]); //print the encrypted text // Encryption = [plainText + secretKey + randomIV] = Cyphertext // // 2. Decryption // for decryption, you will have to use the same IV and key which was used for encryption. // encryptedData = [[StringEncryption alloc] decrypt:encryptedData key:key iv:iv]; // NSString * decryptedText = [[NSString alloc] initWithData:encryptedData encoding:NSUTF8StringEncoding]; // NSLog(@"decrypted data:: %@", decryptedText); //print the decrypted text // For base64EncodingWithLineLength refer - https://github.com/jdg/MGTwitterEngine/blob/master/NSData%2BBase64.m #import "CryptLib.h" #import "NSData+Base64.h" @implementation StringEncryption - (NSData *)encrypt:(NSData *)plainText key:(NSString *)key iv:(NSString *)iv { char keyPointer[kCCKeySizeAES256+2],// room for terminator (unused) ref: https://devforums.apple.com/message/876053#876053 ivPointer[kCCBlockSizeAES128+2]; BOOL patchNeeded; bzero(keyPointer, sizeof(keyPointer)); // fill with zeroes for padding //key = [[StringEncryption alloc] md5:key]; patchNeeded= ([key length] > kCCKeySizeAES256+1); if(patchNeeded) { NSLog(@"Key length is longer %lu", (unsigned long)[[[StringEncryption alloc] md5:key] length]); key = [key substringToIndex:kCCKeySizeAES256]; // Ensure that the key isn't longer than what's needed (kCCKeySizeAES256) } //NSLog(@"md5 :%@", key); [key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding]; [iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding]; if (patchNeeded) { keyPointer[0] = '\0'; // Previous iOS version than iOS7 set the first char to '\0' if the key was longer than kCCKeySizeAES256 } NSUInteger dataLength = [plainText length]; //see https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/CCryptorCreateFromData.3cc.html // For block ciphers, the output size will always be less than or equal to the input size plus the size of one block. size_t buffSize = dataLength + kCCBlockSizeAES128; void *buff = malloc(buffSize); size_t numBytesEncrypted = 0; //refer to http://www.opensource.apple.com/source/CommonCrypto/CommonCrypto-36064/CommonCrypto/CommonCryptor.h //for details on this function //Stateless, one-shot encrypt or decrypt operation. CCCryptorStatus status = CCCrypt(kCCEncrypt, /* kCCEncrypt, etc. */ kCCAlgorithmAES128, /* kCCAlgorithmAES128, etc. */ kCCOptionPKCS7Padding, /* kCCOptionPKCS7Padding, etc. */ keyPointer, kCCKeySizeAES256, /* key and its length */ ivPointer, /* initialization vector - use random IV everytime */ [plainText bytes], [plainText length], /* input */ buff, buffSize,/* data RETURNED here */ &numBytesEncrypted); if (status == kCCSuccess) { return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted]; } free(buff); return nil; } -(NSData *)decrypt:(NSData *)encryptedText key:(NSString *)key iv:(NSString *)iv { char keyPointer[kCCKeySizeAES256+2],// room for terminator (unused) ref: https://devforums.apple.com/message/876053#876053 ivPointer[kCCBlockSizeAES128+2]; BOOL patchNeeded; patchNeeded = ([key length] > kCCKeySizeAES256+1); if(patchNeeded) { NSLog(@"Key length is longer %lu", (unsigned long)[[[StringEncryption alloc] md5:key] length]); key = [key substringToIndex:kCCKeySizeAES256]; // Ensure that the key isn't longer than what's needed (kCCKeySizeAES256) } [key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding]; [iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding]; if (patchNeeded) { keyPointer[0] = '\0'; // Previous iOS version than iOS7 set the first char to '\0' if the key was longer than kCCKeySizeAES256 } NSUInteger dataLength = [encryptedText length]; //see https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/CCryptorCreateFromData.3cc.html // For block ciphers, the output size will always be less than or equal to the input size plus the size of one block. size_t buffSize = dataLength + kCCBlockSizeAES128; void *buff = malloc(buffSize); size_t numBytesEncrypted = 0; //refer to http://www.opensource.apple.com/source/CommonCrypto/CommonCrypto-36064/CommonCrypto/CommonCryptor.h //for details on this function //Stateless, one-shot encrypt or decrypt operation. CCCryptorStatus status = CCCrypt(kCCDecrypt,/* kCCEncrypt, etc. */ kCCAlgorithmAES128, /* kCCAlgorithmAES128, etc. */ kCCOptionPKCS7Padding, /* kCCOptionPKCS7Padding, etc. */ keyPointer, kCCKeySizeAES256,/* key and its length */ ivPointer, /* initialization vector - use same IV which was used for decryption */ [encryptedText bytes], [encryptedText length], //input buff, buffSize,//output &numBytesEncrypted); if (status == kCCSuccess) { return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted]; } free(buff); return nil; } //this function is no longer used in encryption / decryption - (NSString *) md5:(NSString *) input { const char *cStr = [input UTF8String]; unsigned char digest[16]; CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output; } //function to generate random string of given length. //random strings are used as IV - (NSData *)generateRandomIV:(size_t)length { NSMutableData *data = [NSMutableData dataWithLength:length]; int output = SecRandomCopyBytes(kSecRandomDefault, length, data.mutableBytes); NSAssert(output == 0, @"error generating random bytes: %d", errno); return data; } /** * This function computes the SHA256 hash of input string * @param text input text whose SHA256 hash has to be computed * @param length length of the text to be returned * @return returns SHA256 hash of input text */ - (NSString*) sha256:(NSString *)key length:(NSInteger) length{ const char *s=[key cStringUsingEncoding:NSASCIIStringEncoding]; NSData *keyData=[NSData dataWithBytes:s length:strlen(s)]; uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0}; CC_SHA256(keyData.bytes, keyData.length, digest); NSData *out=[NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH]; NSString *hash=[out description]; hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""]; hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""]; hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""]; if(length > [hash length]) { return hash; } else { return [hash substringToIndex:length]; } } @end ================================================ FILE: iOS/NSData+Base64.h ================================================ // // NSData+Base64.h // base64 // // Created by Matt Gallagher on 2009/06/03. // Copyright 2009 Matt Gallagher. All rights reserved. // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. Permission is granted to anyone to // use this software for any purpose, including commercial applications, and to // alter it and redistribute it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source // distribution. // #import void *NewBase64Decode( const char *inputBuffer, size_t length, size_t *outputLength); char *NewBase64Encode( const void *inputBuffer, size_t length, bool separateLines, size_t *outputLength); @interface NSData (Base64) + (NSData *)dataFromBase64String:(NSString *)aString; - (NSString *)base64EncodedString; // added by Hiroshi Hashiguchi - (NSString *)base64EncodedStringWithSeparateLines:(BOOL)separateLines; @end ================================================ FILE: iOS/NSData+Base64.m ================================================ // // NSData+Base64.m // // Derived from http://colloquy.info/project/browser/trunk/NSDataAdditions.h?rev=1576 // Created by khammond on Mon Oct 29 2001. // Formatted by Timothy Hatcher on Sun Jul 4 2004. // Copyright (c) 2001 Kyle Hammond. All rights reserved. // Original development by Dave Winer. // #import "NSData+Base64.h" #import static char encodingTable[64] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' }; @implementation NSData (Base64) + (NSData *) dataWithBase64EncodedString:(NSString *) string { NSData *result = [[NSData alloc] initWithBase64EncodedString:string]; return [result autorelease]; } - (id) initWithBase64EncodedString:(NSString *) string { NSMutableData *mutableData = nil; if( string ) { unsigned long ixtext = 0; unsigned long lentext = 0; unsigned char ch = 0; unsigned char inbuf[3], outbuf[4]; short i = 0, ixinbuf = 0; BOOL flignore = NO; BOOL flendtext = NO; NSData *base64Data = nil; const unsigned char *base64Bytes = nil; // Convert the string to ASCII data. base64Data = [string dataUsingEncoding:NSASCIIStringEncoding]; base64Bytes = [base64Data bytes]; mutableData = [NSMutableData dataWithCapacity:[base64Data length]]; lentext = [base64Data length]; while( YES ) { if( ixtext >= lentext ) break; ch = base64Bytes[ixtext++]; flignore = NO; if( ( ch >= 'A' ) && ( ch <= 'Z' ) ) ch = ch - 'A'; else if( ( ch >= 'a' ) && ( ch <= 'z' ) ) ch = ch - 'a' + 26; else if( ( ch >= '0' ) && ( ch <= '9' ) ) ch = ch - '0' + 52; else if( ch == '+' ) ch = 62; else if( ch == '=' ) flendtext = YES; else if( ch == '/' ) ch = 63; else flignore = YES; if( ! flignore ) { short ctcharsinbuf = 3; BOOL flbreak = NO; if( flendtext ) { if( ! ixinbuf ) break; if( ( ixinbuf == 1 ) || ( ixinbuf == 2 ) ) ctcharsinbuf = 1; else ctcharsinbuf = 2; ixinbuf = 3; flbreak = YES; } inbuf [ixinbuf++] = ch; if( ixinbuf == 4 ) { ixinbuf = 0; outbuf [0] = ( inbuf[0] << 2 ) | ( ( inbuf[1] & 0x30) >> 4 ); outbuf [1] = ( ( inbuf[1] & 0x0F ) << 4 ) | ( ( inbuf[2] & 0x3C ) >> 2 ); outbuf [2] = ( ( inbuf[2] & 0x03 ) << 6 ) | ( inbuf[3] & 0x3F ); for( i = 0; i < ctcharsinbuf; i++ ) [mutableData appendBytes:&outbuf[i] length:1]; } if( flbreak ) break; } } } self = [self initWithData:mutableData]; return self; } - (NSString *) base64EncodingWithLineLength:(unsigned int) lineLength { const unsigned char *bytes = [self bytes]; NSMutableString *result = [NSMutableString stringWithCapacity:[self length]]; unsigned long ixtext = 0; unsigned long lentext = [self length]; long ctremaining = 0; unsigned char inbuf[3], outbuf[4]; short i = 0; short charsonline = 0, ctcopy = 0; unsigned long ix = 0; while( YES ) { ctremaining = lentext - ixtext; if( ctremaining <= 0 ) break; for( i = 0; i < 3; i++ ) { ix = ixtext + i; if( ix < lentext ) inbuf[i] = bytes[ix]; else inbuf [i] = 0; } outbuf [0] = (inbuf [0] & 0xFC) >> 2; outbuf [1] = ((inbuf [0] & 0x03) << 4) | ((inbuf [1] & 0xF0) >> 4); outbuf [2] = ((inbuf [1] & 0x0F) << 2) | ((inbuf [2] & 0xC0) >> 6); outbuf [3] = inbuf [2] & 0x3F; ctcopy = 4; switch( ctremaining ) { case 1: ctcopy = 2; break; case 2: ctcopy = 3; break; } for( i = 0; i < ctcopy; i++ ) [result appendFormat:@"%c", encodingTable[outbuf[i]]]; for( i = ctcopy; i < 4; i++ ) [result appendFormat:@"%c",'=']; ixtext += 3; charsonline += 4; if( lineLength > 0 ) { if (charsonline >= lineLength) { charsonline = 0; [result appendString:@"\n"]; } } } return result; } @end