[
  {
    "path": ".gitignore",
    "content": "Node/node_modules\n"
  },
  {
    "path": "Android/CryptLib.java",
    "content": "package com.pakhee.common;\n\nimport java.io.UnsupportedEncodingException;\nimport java.security.InvalidAlgorithmParameterException;\nimport java.security.InvalidKeyException;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport javax.crypto.BadPaddingException;\nimport javax.crypto.Cipher;\nimport javax.crypto.IllegalBlockSizeException;\nimport javax.crypto.NoSuchPaddingException;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\nimport java.security.SecureRandom;\nimport android.util.Base64;\n\n\t/*****************************************************************\n\t * CrossPlatform CryptLib\n\t * \n\t * <p>\n\t * This cross platform CryptLib uses AES 256 for encryption. This library can\n\t * be used for encryptoion and de-cryption of string on iOS, Android and Windows\n\t * platform.<br/>\n\t * Features: <br/>\n\t * 1. 256 bit AES encryption\n\t * 2. Random IV generation. \n\t * 3. Provision for SHA256 hashing of key. \n\t * </p>\n\t * \n\t * @since 1.0\n\t * @author navneet\n\t *****************************************************************/\n\t \npublic class CryptLib {\n\n\t/**\n\t * Encryption mode enumeration\n\t */\n\tprivate enum EncryptMode {\n\t\tENCRYPT, DECRYPT;\n\t}\n\n\t// cipher to be used for encryption and decryption\n\tCipher _cx;\n\n\t// encryption key and initialization vector\n\tbyte[] _key, _iv;\n\n\tpublic CryptLib() throws NoSuchAlgorithmException, NoSuchPaddingException {\n\t\t// initialize the cipher with transformation AES/CBC/PKCS5Padding\n\t\t_cx = Cipher.getInstance(\"AES/CBC/PKCS5Padding\");\n\t\t_key = new byte[32]; //256 bit key space\n\t\t_iv = new byte[16]; //128 bit IV\n\t}\n\t\n\t/**\n\t * Note: This function is no longer used. \n\t * This function generates md5 hash of the input string\n\t * @param inputString\n\t * @return md5 hash of the input string\n\t */\n\tpublic static final String md5(final String inputString) {\n\t    final String MD5 = \"MD5\";\n\t    try {\n\t        // Create MD5 Hash\n\t        MessageDigest digest = java.security.MessageDigest\n\t                .getInstance(MD5);\n\t        digest.update(inputString.getBytes());\n\t        byte messageDigest[] = digest.digest();\n\n\t        // Create Hex String\n\t        StringBuilder hexString = new StringBuilder();\n\t        for (byte aMessageDigest : messageDigest) {\n\t            String h = Integer.toHexString(0xFF & aMessageDigest);\n\t            while (h.length() < 2)\n\t                h = \"0\" + h;\n\t            hexString.append(h);\n\t        }\n\t        return hexString.toString();\n\n\t    } catch (NoSuchAlgorithmException e) {\n\t        e.printStackTrace();\n\t    }\n\t    return \"\";\n\t}\n\t\n\t/**\n\t * \n\t * @param _inputText\n\t *            Text to be encrypted or decrypted\n\t * @param _encryptionKey\n\t *            Encryption key to used for encryption / decryption\n\t * @param _mode\n\t *            specify the mode encryption / decryption\n\t * @param _initVector\n\t * \t      Initialization vector\n\t * @return encrypted or decrypted string based on the mode\n\t * @throws UnsupportedEncodingException\n\t * @throws InvalidKeyException\n\t * @throws InvalidAlgorithmParameterException\n\t * @throws IllegalBlockSizeException\n\t * @throws BadPaddingException\n\t */\n\t \tprivate String encryptDecrypt(String _inputText, String _encryptionKey,\n\t\t\tEncryptMode _mode, String _initVector) throws UnsupportedEncodingException,\n\t\t\tInvalidKeyException, InvalidAlgorithmParameterException,\n\t\t\tIllegalBlockSizeException, BadPaddingException {\n\t\tString _out = \"\";// output string\n\t\t//_encryptionKey = md5(_encryptionKey);\n\t\t//System.out.println(\"key=\"+_encryptionKey);\n\t\t\n\t\tint len = _encryptionKey.getBytes(\"UTF-8\").length; // length of the key\tprovided\n\t\t\n\t\tif (_encryptionKey.getBytes(\"UTF-8\").length > _key.length)\n\t\t\tlen = _key.length;\n\t\t\n\t\tint ivlen = _initVector.getBytes(\"UTF-8\").length;\n\t\t\n\t\tif(_initVector.getBytes(\"UTF-8\").length > _iv.length)\n\t\t\tivlen = _iv.length;\n\t\t\n\t\tSystem.arraycopy(_encryptionKey.getBytes(\"UTF-8\"), 0, _key, 0, len);\n\t\tSystem.arraycopy(_initVector.getBytes(\"UTF-8\"), 0, _iv, 0, ivlen);\n\t\t//KeyGenerator _keyGen = KeyGenerator.getInstance(\"AES\");\n\t\t//_keyGen.init(128);\n\n\t\tSecretKeySpec keySpec = new SecretKeySpec(_key, \"AES\"); // Create a new SecretKeySpec\n\t\t\t\t\t\t\t\t\t// for the\n\t\t\t\t\t\t\t\t\t// specified key\n\t\t\t\t\t\t\t\t\t// data and\n\t\t\t\t\t\t\t\t\t// algorithm\n\t\t\t\t\t\t\t\t\t// name.\n\t\t\n\t\tIvParameterSpec ivSpec = new IvParameterSpec(_iv); // Create a new\n\t\t\t\t\t\t\t\t// IvParameterSpec\n\t\t\t\t\t\t\t\t// instance with the\n\t\t\t\t\t\t\t\t// bytes from the\n\t\t\t\t\t\t\t\t// specified buffer\n\t\t\t\t\t\t\t\t// iv used as\n\t\t\t\t\t\t\t\t// initialization\n\t\t\t\t\t\t\t\t// vector.\n\n\t\t// encryption\n\t\tif (_mode.equals(EncryptMode.ENCRYPT)) {\n\t\t\t// Potentially insecure random numbers on Android 4.3 and older.\n\t\t\t// Read\n\t\t\t// https://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html\n\t\t\t// for more info.\n\t\t\t_cx.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);// Initialize this cipher instance\n\t\t\tbyte[] results = _cx.doFinal(_inputText.getBytes(\"UTF-8\")); // Finish\n\t\t\t\t\t\t\t\t\t\t// multi-part\n\t\t\t\t\t\t\t\t\t\t// transformation\n\t\t\t\t\t\t\t\t\t\t// (encryption)\n\t\t\t_out = Base64.encodeToString(results, Base64.DEFAULT); // ciphertext\n\t\t\t\t\t\t\t\t\t\t// output\n\t\t}\n\n\t\t// decryption\n\t\tif (_mode.equals(EncryptMode.DECRYPT)) {\n\t\t\t_cx.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);// Initialize this ipher instance\n\t\t\t\n\t\t\tbyte[] decodedValue = Base64.decode(_inputText.getBytes(),\n\t\t\t\t\tBase64.DEFAULT);\n\t\t\tbyte[] decryptedVal = _cx.doFinal(decodedValue); // Finish\n\t\t\t\t\t\t\t\t\t// multi-part\n\t\t\t\t\t\t\t\t\t// transformation\n\t\t\t\t\t\t\t\t\t// (decryption)\n\t\t\t_out = new String(decryptedVal);\n\t\t}\n\t\tSystem.out.println(_out);\n\t\treturn _out; // return encrypted/decrypted string\n\t}\n\n\t/***\n\t * This function computes the SHA256 hash of input string\n\t * @param text input text whose SHA256 hash has to be computed\n\t * @param length length of the text to be returned\n\t * @return returns SHA256 hash of input text \n\t * @throws NoSuchAlgorithmException\n\t * @throws UnsupportedEncodingException\n\t */\n\tpublic static String SHA256 (String text, int length) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n\n\t    String resultStr;\n\t\tMessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n\n\t    md.update(text.getBytes(\"UTF-8\"));\n\t    byte[] digest = md.digest();\n\t    \n\t    StringBuffer result = new StringBuffer();\n\t    for (byte b : digest) {\n\t        result.append(String.format(\"%02x\", b)); //convert to hex\n\t    }\n\t    //return result.toString();\n\t    \n\t    if(length > result.toString().length())\n\t    {\n\t    \tresultStr = result.toString();\n\t    }\n\t    else \n\t    {\n\t    \tresultStr = result.toString().substring(0, length);\n\t    }\n\n\t    return resultStr;\n\t    \n\t}\n\t\n\t/***\n\t * This function encrypts the plain text to cipher text using the key\n\t * provided. You'll have to use the same key for decryption\n\t * \n\t * @param _plainText\n\t *            Plain text to be encrypted\n\t * @param _key\n\t *            Encryption Key. You'll have to use the same key for decryption\n\t * @param _iv\n\t * \t    initialization Vector\n\t * @return returns encrypted (cipher) text\n\t * @throws InvalidKeyException\n\t * @throws UnsupportedEncodingException\n\t * @throws InvalidAlgorithmParameterException\n\t * @throws IllegalBlockSizeException\n\t * @throws BadPaddingException\n\t */\n\t \n\tpublic String encrypt(String _plainText, String _key, String _iv)\n\t\t\tthrows InvalidKeyException, UnsupportedEncodingException,\n\t\t\tInvalidAlgorithmParameterException, IllegalBlockSizeException,\n\t\t\tBadPaddingException {\n\t\treturn encryptDecrypt(_plainText, _key, EncryptMode.ENCRYPT, _iv);\n\t}\n\t\n\t/***\n\t * This funtion decrypts the encrypted text to plain text using the key\n\t * provided. You'll have to use the same key which you used during\n\t * encryprtion\n\t * \n\t * @param _encryptedText\n\t *            Encrypted/Cipher text to be decrypted\n\t * @param _key\n\t *            Encryption key which you used during encryption\n\t * @param _iv\n\t * \t    initialization Vector\n\t * @return encrypted value\n\t * @throws InvalidKeyException\n\t * @throws UnsupportedEncodingException\n\t * @throws InvalidAlgorithmParameterException\n\t * @throws IllegalBlockSizeException\n\t * @throws BadPaddingException\n\t */\n\tpublic String decrypt(String _encryptedText, String _key, String _iv)\n\t\t\tthrows InvalidKeyException, UnsupportedEncodingException,\n\t\t\tInvalidAlgorithmParameterException, IllegalBlockSizeException,\n\t\t\tBadPaddingException {\n\t\treturn encryptDecrypt(_encryptedText, _key, EncryptMode.DECRYPT, _iv);\n\t}\n\t\n\t/**\n \t* this function generates random string for given length\n \t* @param length\n \t* \t\t\t\tDesired length\n \t* * @return \n \t*/\n\tpublic static String generateRandomIV(int length)\n\t{\n\t\tSecureRandom ranGen = new SecureRandom();\n\t\tbyte[] aesKey = new byte[16];\n\t\tranGen.nextBytes(aesKey);\n\t\tStringBuffer result = new StringBuffer();\n\t    for (byte b : aesKey) {\n\t        result.append(String.format(\"%02x\", b)); //convert to hex\n\t    }\n\t    if(length> result.toString().length())\n\t    {\n\t    \treturn result.toString();\n\t    }\n\t    else\n\t    {\n\t    \treturn result.toString().substring(0, length);\n\t    }\n\t}\n}\n"
  },
  {
    "path": "Android/Usage.txt",
    "content": "//This is how to use CryptLib.java\n\n\t   try {\n\t    \tCryptLib _crypt = new CryptLib();\n\t    \tString output= \"\";\n\t    \tString plainText = \"This is the text to be encrypted.\";\n\t    \tString key = CryptLib.SHA256(\"my secret key\", 32); //32 bytes = 256 bit\n\t    \tString iv = CryptLib.generateRandomIV(16); //16 bytes = 128 bit\n\t    \toutput = _crypt.encrypt(plainText, key, iv); //encrypt\n\t    \tSystem.out.println(\"encrypted text=\" + output);\n\t    \toutput = _crypt.decrypt(output, key,iv); //decrypt\n\t    \tSystem.out.println(\"decrypted text=\" + output);\n\t\t} catch (Exception e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\nIf 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\n"
  },
  {
    "path": "C-Sharp/CryptLib.cs",
    "content": "using System;\nusing System.Text;\nusing System.Security.Cryptography;\n\nnamespace com.pakhee.common\n{\n\t/*****************************************************************\n\t * CrossPlatform CryptLib\n\t * \n\t * <p>\n\t * This cross platform CryptLib uses AES 256 for encryption. This library can\n\t * be used for encryptoion and de-cryption of string on iOS, Android and Windows\n\t * platform.<br/>\n\t * Features: <br/>\n\t * 1. 256 bit AES encryption\n\t * 2. Random IV generation. \n\t * 3. Provision for SHA256 hashing of key. \n\t * </p>\n\t * \n\t * @since 1.0\n\t * @author navneet\n\t *****************************************************************/\n\tpublic class CryptLib\n\t{\n\t\tUTF8Encoding _enc;\n\t\tRijndaelManaged _rcipher;\n\t\tbyte[] _key, _pwd, _ivBytes, _iv;\n\t\t\n\t\t/***\n\t\t * Encryption mode enumeration\n\t\t */\n\t\tprivate enum EncryptMode {ENCRYPT, DECRYPT};\n\t\t\n\t\tstatic readonly char[] CharacterMatrixForRandomIVStringGeneration = {\n\t\t\t'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', \n\t\t\t'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', \n\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', \n\t\t\t'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', \n\t\t\t'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'\n\t\t};\n\t\t\n\t\t/**\n\t\t * This function generates random string of the given input length.\n\t\t * \n\t\t * @param _plainText\n\t\t *            Plain text to be encrypted\n\t\t * @param _key\n\t\t *            Encryption Key. You'll have to use the same key for decryption\n\t\t * @return returns encrypted (cipher) text\n\t\t */\n\t\tinternal static string GenerateRandomIV(int length) {\n\t\t\tchar[] _iv = new char[length];\n\t\t\tbyte[] randomBytes = new byte[length];\n\n\t\t\tusing (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) {\n\t\t\t\trng.GetBytes(randomBytes); //Fills an array of bytes with a cryptographically strong sequence of random values. \n\t\t\t}\n\n\t\t\tfor (int i = 0; i < _iv.Length; i++) {\n\t\t\t\tint ptr = randomBytes[i] % CharacterMatrixForRandomIVStringGeneration.Length;\n\t\t\t\t_iv[i] = CharacterMatrixForRandomIVStringGeneration[ptr];\n\t\t\t}\n\n\t\t\treturn new string(_iv);\n\t\t}\n\t\t\n\t\t\n\n\t\tpublic CryptLib()\n\t\t{\n\t\t\t_enc = new UTF8Encoding();\n\t\t\t_rcipher =  new RijndaelManaged();\n\t\t\t_rcipher.Mode = CipherMode.CBC;\n\t\t\t_rcipher.Padding = PaddingMode.PKCS7;\n\t\t\t_rcipher.KeySize = 256;\n\t\t\t_rcipher.BlockSize = 128;\n\t\t\t_key = new byte[32];\n\t\t\t_iv = new byte[_rcipher.BlockSize/8]; //128 bit / 8 = 16 bytes\n\t\t\t_ivBytes =  new byte[16];\n\t\t}\n\n\t\t/**\n\t\t * \n\t\t * @param _inputText\n\t\t *            Text to be encrypted or decrypted\n\t\t * @param _encryptionKey\n\t\t *            Encryption key to used for encryption / decryption\n\t\t * @param _mode\n\t\t *            specify the mode encryption / decryption\n\t\t * @param _initVector\n\t\t * \t\t\t  initialization vector\n\t\t * @return encrypted or decrypted string based on the mode\n\t \t*/\n\t\tprivate String encryptDecrypt (string _inputText, string _encryptionKey, EncryptMode _mode, string _initVector)\n\t\t{\n\n\t\t\tstring _out = \"\";// output string\n\t\t\t//_encryptionKey = MD5Hash (_encryptionKey);\n\t\t\t_pwd = Encoding.UTF8.GetBytes(_encryptionKey);\n\t\t\t_ivBytes = Encoding.UTF8.GetBytes (_initVector);\n\n\t\t\tint len = _pwd.Length;\n\t\t\tif (len > _key.Length)\n\t\t\t{\n\t\t\t\tlen = _key.Length;\n\t\t\t}\n\t\t\tint ivLenth = _ivBytes.Length;\n\t\t\tif (ivLenth > _iv.Length) \n\t\t\t{\n\t\t\t\tivLenth = _iv.Length;\t\t\n\t\t\t}\n\n\t\t\tArray.Copy(_pwd, _key, len);\n\t\t\tArray.Copy (_ivBytes, _iv, ivLenth);\n\t\t\t_rcipher.Key = _key;\n\t\t\t_rcipher.IV = _iv;\n\n\t\t\tif (_mode.Equals (EncryptMode.ENCRYPT)) {\n\t\t\t\t//encrypt\n\t\t\t\tbyte[] plainText = _rcipher.CreateEncryptor().TransformFinalBlock(_enc.GetBytes(_inputText) , 0, _inputText.Length);\n\t\t\t\t_out = Convert.ToBase64String(plainText);\n\t\t\t}\n\t\t\tif (_mode.Equals (EncryptMode.DECRYPT)) {\n\t\t\t\t//decrypt\n\t\t\t\tbyte[] plainText = _rcipher.CreateDecryptor().TransformFinalBlock(Convert.FromBase64String(_inputText), 0, Convert.FromBase64String(_inputText).Length);\n\t\t\t\t_out = _enc.GetString(plainText);\n\t\t\t}\n\t\t\t_rcipher.Dispose();\n\t\t\treturn _out;// return encrypted/decrypted string\n\t\t}\n\n\t\t/**\n\t\t * This function encrypts the plain text to cipher text using the key\n\t\t * provided. You'll have to use the same key for decryption\n\t\t * \n\t\t * @param _plainText\n\t\t *            Plain text to be encrypted\n\t\t * @param _key\n\t\t *            Encryption Key. You'll have to use the same key for decryption\n\t\t * @return returns encrypted (cipher) text\n\t\t */\n\t\tpublic string encrypt (string _plainText, string _key, string _initVector)\n\t\t{\n\t\t\treturn encryptDecrypt(_plainText, _key, EncryptMode.ENCRYPT, _initVector);\n\t\t}\n\n\t\t/***\n\t\t * This funtion decrypts the encrypted text to plain text using the key\n\t\t * provided. You'll have to use the same key which you used during\n\t\t * encryprtion\n\t\t * \n\t\t * @param _encryptedText\n\t\t *            Encrypted/Cipher text to be decrypted\n\t\t * @param _key\n\t\t *            Encryption key which you used during encryption\n\t\t * @return encrypted value\n\t\t */\n\t\t \n\t\tpublic string decrypt(string _encryptedText, string _key, string _initVector)\n\t\t{\n\t\t\treturn encryptDecrypt(_encryptedText, _key, EncryptMode.DECRYPT, _initVector);\n\t\t}\n\n\t\t/***\n\t\t * This function decrypts the encrypted text to plain text using the key\n\t\t * provided. You'll have to use the same key which you used during\n\t\t * encryption\n\t\t * \n\t\t * @param _encryptedText\n\t\t *            Encrypted/Cipher text to be decrypted\n\t\t * @param _key\n\t\t *            Encryption key which you used during encryption\n\t\t */\n\t\tpublic static string getHashSha256(string text, int length)\n\t\t{\n\t\t\tbyte[] bytes = Encoding.UTF8.GetBytes(text);\n\t\t\tSHA256Managed hashstring = new SHA256Managed();\n\t\t\tbyte[] hash = hashstring.ComputeHash(bytes);\n\t\t\tstring hashString = string.Empty;\n\t\t\tforeach (byte x in hash)\n\t\t\t{\n\t\t\t\thashString += String.Format(\"{0:x2}\", x); //covert to hex string\n\t\t\t}\n\t\t\tif (length > hashString.Length)\n\t\t\t\treturn hashString;\n\t\t\telse\n\t\t\t\treturn hashString.Substring (0, length);\n\t\t}\n\t\t\n\t\t//this function is no longer used.\n\t\tprivate static string MD5Hash(string text)\n\t\t{\n\t\t\tMD5 md5 = new MD5CryptoServiceProvider();\n\n\t\t\t//compute hash from the bytes of text\n\t\t\tmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));\n\n\t\t\t//get hash result after compute it\n\t\t\tbyte[] result = md5.Hash;\n\n\t\t\tStringBuilder strBuilder = new StringBuilder();\n\t\t\tfor (int i = 0; i < result.Length; i++)\n\t\t\t{\n\t\t\t\t//change it into 2 hexadecimal digits\n\t\t\t\t//for each byte\n\t\t\t\tstrBuilder.Append(result[i].ToString(\"x2\"));\n\t\t\t}\n\t\t\tConsole.WriteLine (\"md5 hash of they key=\" + strBuilder.ToString ());\n\t\t\treturn strBuilder.ToString();\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "C-Sharp/HowToUse.cs",
    "content": "\tpublic class test {\n\t\tpublic static void Main (String []args)\n\t\t{\n\t\t\tCryptLib _crypt = new CryptLib ();\n\t\t\tstring plainText = \"This is the text to be encrypted\";\n\t\t\tString iv = CryptLib.GenerateRandomIV (16); //16 bytes = 128 bits\n\t\t\tstring key = CryptLib.getHashSha256(\"my secret key\", 31); //32 bytes = 256 bits\n\t\t\tString cypherText = _crypt.encrypt (plainText, key, iv);\n\t\t\tConsole.WriteLine (\"iv=\"+iv);\n\t\t\tConsole.WriteLine (\"key=\" + key);\n\t\t\tConsole.WriteLine(\"Cypher text=\" + cypherText);\n\t\t\tConsole.WriteLine (\"Plain text =\" + _crypt.decrypt (cypherText, key, iv));\n\t\t}\n\n\t}\n"
  },
  {
    "path": "LICENSE",
    "content": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2015 NAVNEET KUMAR\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "Node/README.md",
    "content": "CryptLib\r\n=========\r\n\r\nA module to encrypt/decrypt string in Node, written in ES6 (src folder) and transpiled using Babel to ES5(dist folder).\r\n\r\nUsing companion framework libraries, you should be able to encrypt/decrypt between node, iOS, Android and Windows platforms.\r\n\r\nCompanion libs can be found here: https://github.com/Pakhee/Cross-platform-AES-encryption\r\n\r\n\r\n## Installation\r\n\r\n  npm install cryptlib --save\r\n\r\n## Usage\r\n\r\n\tvar CryptLib = require('cryptlib'),\r\n\t\t_crypt = new CryptLib(),\r\n\t\tplainText = 'This is the text to be encrypted',\r\n\t\tiv = _crypt.generateRandomIV(16), //16 bytes = 128 bit\r\n\t\tkey = _crypt.getHashSha256('my secret key', 32), //32 bytes = 256 bits\r\n\t\tcypherText = _crypt.encrypt(plainText, key, iv),\r\n        originalText = _crypt.decrypt(cypherText, key, iv);\r\n\r\n## Run Code Sample\r\n  \r\n  npm start\r\n\r\n## Tests\r\n\r\n  npm test\r\n\r\n## Contributing\r\n\r\nIn lieu of a formal styleguide, take care to maintain the existing coding style.\r\nAdd unit tests for any new or changed functionality. Lint and test your code.\r\n\r\n## Release History\r\n\r\n* 0.1.0 Initial release\r\n\r\n## License\r\n\r\nApache License; see [LICENSE](../LICENSE).\r\n\r\n(c) 2015 by Abdul Khan\r\n"
  },
  {
    "path": "Node/dist/CryptLib.js",
    "content": "\n/*global console*/\n'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n  value: true\n});\n\nvar _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; }; })();\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nvar _crypto = require('crypto');\n\nvar _crypto2 = _interopRequireDefault(_crypto);\n\nvar _bl = require('bl');\n\nvar _bl2 = _interopRequireDefault(_bl);\n\nvar _lodashIsarray = require('lodash.isarray');\n\nvar _lodashIsarray2 = _interopRequireDefault(_lodashIsarray);\n\n/**\n * CrossPlatform CryptLib\n   * This cross platform CryptLib uses AES 256 for encryption. This library can\n   * be used for encryption and de-cryption of strings on iOS, Android, Windows\n   * and Node platform.\n   * Features:\n   * 1. 256 bit AES encryption\n   * 2. Random IV generation. \n   * 3. Provision for SHA256 hashing of key. \n */\n\nvar CryptLib = (function () {\n  function CryptLib() {\n    _classCallCheck(this, CryptLib);\n\n    this._maxKeySize = 32;\n    this._maxIVSize = 16;\n    this._algorithm = 'AES-256-CBC';\n    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', '-', '_'];\n  }\n\n  _createClass(CryptLib, [{\n    key: '_encryptDecrypt',\n\n    /**\n     * private function: _encryptDecrypt\n     * encryptes or decrypts to or from text or encrypted text given an iv and key\n     * @param  {string}  text        can be plain text or encrypted text\n     * @param  {string}  key         the key used to encrypt or decrypt \n     * @param  {string}  initVector  the initialization vector to encrypt or \n     *                               decrypt\n     * @param  {bool}    isEncrypt   true = encryption, false = decryption\n     * @return {string}              encryted text or plain text \n     */\n    value: function _encryptDecrypt(text, key, initVector, isEncrypt) {\n\n      if (!text || !key) {\n        throw 'cryptLib._encryptDecrypt: -> key and plain or encrypted text ' + 'required';\n      }\n\n      var ivBl = new _bl2['default'](),\n          keyBl = new _bl2['default'](),\n          keyCharArray = key.split(''),\n          ivCharArray = [],\n          encryptor = undefined,\n          decryptor = undefined,\n          clearText = undefined;\n\n      if (initVector && initVector.length > 0) {\n        ivCharArray = initVector.split('');\n      }\n\n      for (var i = 0; i < this._maxIVSize; i++) {\n        ivBl.append(ivCharArray.shift() || [null]);\n      }\n\n      for (var i = 0; i < this._maxKeySize; i++) {\n        keyBl.append(keyCharArray.shift() || [null]);\n      }\n\n      if (isEncrypt) {\n        encryptor = _crypto2['default'].createCipheriv(this._algorithm, keyBl.toString(), ivBl.toString());\n        encryptor.setEncoding('base64');\n        encryptor.write(text);\n        encryptor.end();\n        return encryptor.read();\n      }\n\n      decryptor = _crypto2['default'].createDecipheriv(this._algorithm, keyBl.toString(), ivBl.toString());\n      var dec = decryptor.update(text, 'base64', 'utf8');\n      dec += decryptor.final('utf8');\n      return dec;\n    }\n  }, {\n    key: '_isCorrectLength',\n\n    /**\n     * private function: _isCorrectLength \n     * checks if length is preset and is a whole number and > 0\n     * @param  {int}  length\n     * @return {bool} \n    */\n    value: function _isCorrectLength(length) {\n      return length && /^\\d+$/.test(length) && parseInt(length, 10) !== 0;\n    }\n  }, {\n    key: 'generateRandomIV',\n\n    /**\n     * generates random initaliztion vector given a length\n     * @param  {int}  length  the length of the iv to be generated\n     */\n    value: function generateRandomIV(length) {\n      if (!this._isCorrectLength(length)) {\n        throw 'cryptLib.generateRandomIV() -> needs length or in wrong format';\n      }\n\n      length = parseInt(length, 10);\n      var _iv = [],\n          randomBytes = _crypto2['default'].randomBytes(length);\n\n      for (var i = 0; i < length; i++) {\n        var ptr = randomBytes[i] % this._characterMatrixForRandomIVStringGeneration.length;\n        _iv[i] = this._characterMatrixForRandomIVStringGeneration[ptr];\n      }\n      return _iv.join('');\n    }\n  }, {\n    key: 'getHashSha256',\n\n    /**\n     * Creates a hash of a key using SHA-256 algorithm\n     * @param  {string} key     the key that will be hashed\n     * @param  {int}    length  the length of the SHA-256 hash\n     * @return {string}         the output hash generated given a key and length\n     */\n    value: function getHashSha256(key, length) {\n      if (!key) {\n        throw 'cryptLib.getHashSha256() -> needs key';\n      }\n\n      if (!this._isCorrectLength(length)) {\n        throw 'cryptLib.getHashSha256() -> needs length or in wrong format';\n      }\n\n      return _crypto2['default'].createHash('sha256').update(key).digest('hex').substring(0, length);\n    }\n  }, {\n    key: 'encrypt',\n\n    /**\n     * encryptes plain text given a key and initialization vector\n     * @param  {string}  text        can be plain text or encrypted text\n     * @param  {string}  key         the key used to encrypt or decrypt \n     * @param  {string}  initVector  the initialization vector to encrypt or \n     *                               decrypt\n     * @return {string}              encryted text or plain text \n     */\n    value: function encrypt(plainText, key, initVector) {\n      return this._encryptDecrypt(plainText, key, initVector, true);\n    }\n  }, {\n    key: 'decrypt',\n\n    /**\n     * decrypts encrypted text given a key and initialization vector\n     * @param  {string}  text        can be plain text or encrypted text\n     * @param  {string}  key         the key used to encrypt or decrypt \n     * @param  {string}  initVector  the initialization vector to encrypt or \n     *                               decrypt\n     * @return {string}              encryted text or plain text \n     */\n    value: function decrypt(encryptedText, key, initVector) {\n      return this._encryptDecrypt(encryptedText, key, initVector, false);\n    }\n  }]);\n\n  return CryptLib;\n})();\n\nexports['default'] = CryptLib;\nmodule.exports = exports['default'];"
  },
  {
    "path": "Node/gulpfile.js",
    "content": "var gulp = require('gulp');\r\nvar babel = require('gulp-babel');\r\nvar mocha = require('gulp-mocha');\r\n\r\ngulp.task('babel', function() {\r\n  return gulp.src('src/*.js')\r\n    .pipe(babel())\r\n    .pipe(gulp.dest('dist/'));\r\n});\r\n\r\ngulp.task('watch', function() {\r\n  gulp.watch('src/*.js', ['babel']);\r\n});\r\n\r\ngulp.task('test', ['babel'], function() {\r\n  return gulp.src(['test/*.js'])\r\n    .pipe(mocha({ reporter: 'spec' }))\r\n    .on('error', function(err) {\r\n        console.log(err.stack);\r\n    });\r\n});\r\n\r\n// Default Task\r\ngulp.task('default', ['babel', 'test']);\r\n"
  },
  {
    "path": "Node/index.js",
    "content": "/*global require*/\r\n\r\nvar CryptLib = require('cryptlib'),\r\n    _crypt = new CryptLib(),\r\n    plainText = 'This is the text to be encrypted',\r\n    iv = _crypt.generateRandomIV(16), //16 bytes = 128 bit\r\n    key = _crypt.getHashSha256('my secret key', 32), //32 bytes = 256 bits\r\n    cypherText = _crypt.encrypt(plainText, key, iv);\r\n\r\nconsole.log('iv = %s', iv);\r\nconsole.log('key = %s', key);\r\nconsole.log('Cypher text = %s', cypherText);\r\nconsole.log('Plain text = %s', _crypt.decrypt(cypherText, key, iv));"
  },
  {
    "path": "Node/package.json",
    "content": "{\n  \"name\": \"cryptlib\",\n  \"version\": \"1.0.0\",\n  \"author\": {\n    \"name\": \"Abdul Khan\"\n  },\n  \"main\": \"dist/CryptLib.js\",\n  \"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\",\n  \"contributors\": [\n    {\n      \"name\": \"Abdul Khan\",\n      \"email\": \"invalidred@gmail.com\"\n    },\n    {\n      \"name\": \"Alexey Novak\",\n      \"email\": \"alexey.novak.mail@gmail.com\"\n    }\n  ],\n  \"scripts\": {\n    \"start\": \"node index.js\",\n    \"test\": \"node node_modules/mocha/bin/mocha --reporter spec test/*\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+ssh://git@github.com:invalidred/Cross-platform-AES-encryption.git\"\n  },\n  \"keywords\": [\n    \"AES node\",\n    \"Cross Platform\",\n    \"Encryption\",\n    \"Decryption\"\n  ],\n  \"dependencies\": {\n    \"bl\": \"4.0.3\",\n    \"lodash.isarray\": \"3.0.4\",\n    \"lodash.isfunction\": \"3.0.6\"\n  },\n  \"devDependencies\": {\n    \"babel\": \"^5.2.17\",\n    \"chai\": \"^2.3.0\",\n    \"gulp\": \"^3.8.11\",\n    \"gulp-babel\": \"^5.1.0\",\n    \"gulp-mocha\": \"^2.0.1\",\n    \"mocha\": \"^2.2.4\"\n  },\n  \"engine\": \"node >= 0.10.x\",\n  \"homepage\": \"https://github.com/invalidred/Cross-platform-AES-encryption\",\n  \"bugs\": {\n    \"url\": \"https://github.com/Pakhee/Cross-platform-AES-encryption/issues\"\n  },\n  \"private\": false,\n  \"license\": \"Apache\",\n  \"_npmVersion\": \"2.5.1\",\n  \"_nodeVersion\": \"0.12.0\",\n  \"_npmUser\": {\n    \"name\": \"invalidred\",\n    \"email\": \"invalidred@gmail.com\"\n  },\n  \"maintainers\": [\n    {\n      \"name\": \"Abdul Khan\",\n      \"email\": \"invalidred@gmail.com\"\n    }\n  ]\n}\n"
  },
  {
    "path": "Node/src/CryptLib.js",
    "content": "\n/*global console*/\n'use strict';\n\nimport crypto from 'crypto';\nimport BufferList from 'bl';\nimport isArray from 'lodash.isarray';\n\n/**\n * CrossPlatform CryptLib\n   * This cross platform CryptLib uses AES 256 for encryption. This library can\n   * be used for encryption and de-cryption of strings on iOS, Android, Windows\n   * and Node platform.\n   * Features:\n   * 1. 256 bit AES encryption\n   * 2. Random IV generation. \n   * 3. Provision for SHA256 hashing of key. \n */\nexport default class CryptLib {\n\n  constructor() {\n    this._maxKeySize = 32;\n    this._maxIVSize = 16;\n    this._algorithm = 'AES-256-CBC';\n    this._characterMatrixForRandomIVStringGeneration = [\n      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', \n      'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', \n      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', \n      'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', \n      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'\n    ];\n  }\n\n  /**\n   * private function: _encryptDecrypt\n   * encryptes or decrypts to or from text or encrypted text given an iv and key\n   * @param  {string}  text        can be plain text or encrypted text\n   * @param  {string}  key         the key used to encrypt or decrypt \n   * @param  {string}  initVector  the initialization vector to encrypt or \n   *                               decrypt\n   * @param  {bool}    isEncrypt   true = encryption, false = decryption\n   * @return {string}              encryted text or plain text \n   */\n  _encryptDecrypt(text, key, initVector, isEncrypt) {\n\n    if (!text || !key) {\n      throw 'cryptLib._encryptDecrypt: -> key and plain or encrypted text '+\n       'required';\n    }\n\n    let ivBl = new BufferList(),\n        keyBl = new BufferList(),\n        keyCharArray = key.split(''),\n        ivCharArray = [],\n        encryptor, decryptor, clearText;\n\n    if (initVector && initVector.length > 0) {\n       ivCharArray = initVector.split('');\n    }\n    \n    for (var i = 0; i < this._maxIVSize; i++) {\n      ivBl.append(ivCharArray.shift() || [null]);\n    }\n\n    for (var i = 0; i < this._maxKeySize; i++) {\n      keyBl.append(keyCharArray.shift() || [null]);\n    }\n\n    if (isEncrypt) {\n      encryptor = crypto.createCipheriv(this._algorithm, keyBl.toString(), \n        ivBl.toString());\n      encryptor.setEncoding('base64');\n      encryptor.write(text);\n      encryptor.end();\n      return encryptor.read();\n    }\n\n    decryptor = crypto.createDecipheriv(this._algorithm, keyBl.toString(),\n      ivBl.toString());\n    var dec = decryptor.update(text, 'base64', 'utf8');\n    dec += decryptor.final('utf8');\n    return dec;\n  }\n\n  /**\n   * private function: _isCorrectLength \n   * checks if length is preset and is a whole number and > 0\n   * @param  {int}  length\n   * @return {bool} \n  */\n  _isCorrectLength(length) {\n    return length && /^\\d+$/.test(length) && parseInt(length, 10) !== 0\n  }\n\n  /**\n   * generates random initaliztion vector given a length\n   * @param  {int}  length  the length of the iv to be generated\n   */\n  generateRandomIV(length) {\n    if (!this._isCorrectLength(length)) {\n      throw 'cryptLib.generateRandomIV() -> needs length or in wrong format';\n    }\n\n    length = parseInt(length, 10);\n    let _iv = [],\n        randomBytes = crypto.randomBytes(length);\n\n    for (let i = 0; i < length; i++) {\n      let ptr = randomBytes[i] % \n        this._characterMatrixForRandomIVStringGeneration.length;\n      _iv[i] = this._characterMatrixForRandomIVStringGeneration[ptr];\n    }\n    return _iv.join('');\n  }\n\n  /**\n   * Creates a hash of a key using SHA-256 algorithm\n   * @param  {string} key     the key that will be hashed\n   * @param  {int}    length  the length of the SHA-256 hash\n   * @return {string}         the output hash generated given a key and length\n   */\n  getHashSha256(key, length) {\n    if (!key) {\n      throw 'cryptLib.getHashSha256() -> needs key';\n    }\n\n    if (!this._isCorrectLength(length)) {\n      throw 'cryptLib.getHashSha256() -> needs length or in wrong format';\n    }\n\n    return crypto.createHash('sha256')\n                 .update(key)\n                 .digest('hex')\n                 .substring(0, length);\n  }\n\n  /**\n   * encryptes plain text given a key and initialization vector\n   * @param  {string}  text        can be plain text or encrypted text\n   * @param  {string}  key         the key used to encrypt or decrypt \n   * @param  {string}  initVector  the initialization vector to encrypt or \n   *                               decrypt\n   * @return {string}              encryted text or plain text \n   */\n  encrypt(plainText, key, initVector) {\n    return this._encryptDecrypt(plainText, key, initVector, true);\n  }\n\n  /**\n   * decrypts encrypted text given a key and initialization vector\n   * @param  {string}  text        can be plain text or encrypted text\n   * @param  {string}  key         the key used to encrypt or decrypt \n   * @param  {string}  initVector  the initialization vector to encrypt or \n   *                               decrypt\n   * @return {string}              encryted text or plain text \n   */\n  decrypt(encryptedText, key, initVector) {\n    return this._encryptDecrypt(encryptedText, key, initVector, false);\n  }\n}\n"
  },
  {
    "path": "Node/test/CryptLib-test.js",
    "content": "/*global it, describe, require*/\r\n\r\nvar chai = require('chai'),\r\n    expect = chai.expect,\r\n    CryptLib = require('../dist/cryptLib.js');\r\n\r\ndescribe('CryptLib', function() {\r\n  var cryptLib;\r\n\r\n  before(function() {\r\n    cryptLib = new CryptLib();\r\n  });\r\n\r\n  after(function() {\r\n    cryptLib = null;\r\n  });\r\n\r\n  describe('generateRandomIV()', function() {\r\n    var errorMessage = 'cryptLib.generateRandomIV() -> needs length or in wrong format';\r\n\r\n    it('no length should throw error', function() {\r\n      try {\r\n        cryptLib.generateRandomIV()\r\n      } catch (message) {\r\n        expect(message).to.equal(errorMessage);\r\n      }\r\n    });\r\n\r\n    it('non-numeric and non-whole number length should throw error', function() {\r\n      try{\r\n        cryptLib.generateRandomIV('abc');\r\n      } catch (message) {\r\n        expect(message).to.equal(errorMessage);\r\n      }\r\n\r\n      try{\r\n        cryptLib.generateRandomIV('12a'); \r\n      } catch (message) {\r\n        expect(message).to.equal(errorMessage);\r\n      }\r\n\r\n      try{\r\n        cryptLib.generateRandomIV('12.2'); \r\n      } catch (message) {\r\n        expect(message).to.equal(errorMessage);\r\n      }\r\n    });\r\n\r\n    it('negative length should throw error', function() {\r\n      try {\r\n        cryptLib.generateRandomIV('-1');\r\n      } catch (message) {\r\n        expect(message).to.equal(errorMessage);\r\n      }\r\n    });\r\n\r\n    it('length = 0, should throw error', function() {\r\n      try {\r\n        cryptLib.generateRandomIV(0);\r\n      } catch (message) {\r\n        expect(message).to.equal(errorMessage);\r\n      }\r\n\r\n      try {\r\n        cryptLib.generateRandomIV('0');\r\n      } catch (message) {\r\n        expect(message).to.equal(errorMessage);\r\n      }\r\n    });\r\n\r\n    it('length = 2', function() {\r\n      var iv = cryptLib.generateRandomIV(2);\r\n      expect(iv).to.have.length(2);\r\n      expect(iv).to.be.string;\r\n    });\r\n\r\n    it('length = 100', function() {\r\n      var iv = cryptLib.generateRandomIV(100);\r\n      expect(iv).to.have.length(100);\r\n      expect(iv).to.be.string;\r\n    });\r\n  });\r\n\r\n  describe('getHashSha256()', function() {\r\n    var lengthErrorMessage = 'cryptLib.getHashSha256() -> needs length or in wrong format',\r\n        keyErrorMessage = 'cryptLib.getHashSha256() -> needs key',\r\n        validKey = 'key';\r\n\r\n    it('no key should throw error', function() {\r\n      try {\r\n        cryptLib.getHashSha256(null,2);\r\n      } catch (message) {\r\n        expect(message).to.equal(keyErrorMessage);\r\n      }\r\n    });\r\n\r\n    it('no length should throw error', function() {\r\n      try {\r\n        cryptLib.getHashSha256(validKey, null);\r\n      } catch (message) {\r\n        expect(message).to.equal(lengthErrorMessage);\r\n      }\r\n    });\r\n\r\n    it('non-numeric and non-whole number length should throw error', function() {\r\n      try{\r\n        cryptLib.getHashSha256(validKey, 'abc');\r\n      } catch (message) {\r\n        expect(message).to.equal(lengthErrorMessage);\r\n      }\r\n\r\n      try{\r\n        cryptLib.getHashSha256(validKey, '12a'); \r\n      } catch (message) {\r\n        expect(message).to.equal(lengthErrorMessage);\r\n      }\r\n\r\n      try{\r\n        cryptLib.getHashSha256(validKey, '12.2'); \r\n      } catch (message) {\r\n        expect(message).to.equal(lengthErrorMessage);\r\n      }\r\n    });\r\n\r\n    it('negative length should throw error', function() {\r\n      try {\r\n        cryptLib.getHashSha256(validKey, '-1');\r\n      } catch (message) {\r\n        expect(message).to.equal(lengthErrorMessage);\r\n      }\r\n\r\n      try {\r\n        cryptLib.getHashSha256(validKey, -1);\r\n      } catch (message) {\r\n        expect(message).to.equal(lengthErrorMessage);\r\n      }\r\n    });\r\n\r\n    it('length = 0, should throw error', function() {\r\n      try {\r\n        cryptLib.getHashSha256(validKey, 0);\r\n      } catch (message) {\r\n        expect(message).to.equal(lengthErrorMessage);\r\n      }\r\n\r\n      try {\r\n        cryptLib.getHashSha256(validKey, '0');\r\n      } catch (message) {\r\n        expect(message).to.equal(lengthErrorMessage);\r\n      }\r\n    });\r\n\r\n    it('valid key with length = 2', function() {\r\n      var sha = cryptLib.getHashSha256(validKey, 2);\r\n      expect(sha).to.have.length(2);\r\n      expect(sha).to.be.string;\r\n    });\r\n\r\n    it('valid key with length = 64', function() {\r\n      var sha = cryptLib.getHashSha256(validKey, 64);\r\n      expect(sha).to.have.length(64);\r\n      expect(sha).to.be.string;\r\n    });\r\n\r\n    it('valid key with length = 100 should return 64 char sha', function() {\r\n      var sha = cryptLib.getHashSha256(validKey, 100);\r\n      expect(sha).to.have.length(64);\r\n      expect(sha).to.be.string;\r\n    });\r\n  });\r\n\r\n  describe('encrypt() and decrypt() tests', function() {\r\n    var errorMessage = 'cryptLib._encryptDecrypt: -> key and plain or encrypted text required',\r\n        plainText = 'This is the plain text that will be encrypted and decrypted',\r\n        myKey = 'myKey';\r\n\r\n    it('encrypt() with no plain text should throw error', function() {\r\n      try {\r\n        cryptLib.encrypt(null, 'key123', 'iv123');\r\n      } catch(error) {\r\n        expect(error).to.equal(errorMessage);\r\n      }\r\n    });\r\n\r\n    it('encrypt() with no key should throw error', function() {\r\n      try {\r\n        cryptLib.encrypt(plainText, null, 'iv123');\r\n      } catch(error) {\r\n        expect(error).to.equal(errorMessage);\r\n      }\r\n    });\r\n\r\n    it('basic encrypt() decrypt() locally : 0 char iv and 2 char key', function() {\r\n      var iv = '',\r\n          keyHashed = cryptLib.getHashSha256(myKey, 2),\r\n          encryptedText = cryptLib.encrypt(plainText, keyHashed, iv),\r\n          regularText = cryptLib.decrypt(encryptedText, keyHashed, iv);\r\n      expect(regularText).to.equal(plainText);\r\n    });\r\n\r\n    it('basic encrypt() decrypt() locally : 2 char iv and 2 char key', function() {\r\n      var iv = cryptLib.generateRandomIV(2),\r\n          keyHashed = cryptLib.getHashSha256(myKey, 2),\r\n          encryptedText = cryptLib.encrypt(plainText, keyHashed, iv),\r\n          decryptedText = cryptLib.decrypt(encryptedText, keyHashed, iv);\r\n      expect(decryptedText).to.equal(plainText);\r\n    });\r\n\r\n    it('basic encrypt() decrypt() locally : 16 char iv and 32 char key', function() {\r\n      var iv = cryptLib.generateRandomIV(16),\r\n          keyHashed = cryptLib.getHashSha256(myKey, 32),\r\n          encryptedText = cryptLib.encrypt(plainText, keyHashed, iv),\r\n          decryptedText = cryptLib.decrypt(encryptedText, keyHashed, iv);\r\n      expect(decryptedText).to.equal(plainText);\r\n    });\r\n\r\n    it('basic encrypt() decrypt() locally : 20 char iv and 80 char key', function() {\r\n      var iv = cryptLib.generateRandomIV(20),\r\n          keyHashed = cryptLib.getHashSha256(myKey, 80),\r\n          encryptedText = cryptLib.encrypt(plainText, keyHashed, iv),\r\n          decryptedText = cryptLib.decrypt(encryptedText, keyHashed, iv);\r\n      expect(decryptedText).to.equal(plainText);\r\n    });\r\n\r\n    it('decrypt 0 char iv and 2 char key generated by c#', function() {\r\n      var cSharpIv = '',\r\n          cSharpKey = 'b1',\r\n          cSharpPlainText = 'C# text that\\'s going to be decrypted',\r\n          cSharpCipher = 'M2rfrn9DqNHJe3Hev9nMxKKgIHoqUsc7FJM+tBGxIrl3Wk9UeKIQ5fRUUZF3q2i5',\r\n          nodeDecrpytedText;\r\n      nodeDecrpytedText = cryptLib.decrypt(cSharpCipher, cSharpKey, cSharpIv);\r\n      expect(nodeDecrpytedText).to.equal(cSharpPlainText);\r\n    });\r\n\r\n    it('decrypt 2 char iv and 2 char key generated by c#', function() {\r\n      var cSharpIv = 'sA',\r\n          cSharpKey = 'b1',\r\n          cSharpPlainText = 'C# text that\\'s going to be decrypted',\r\n          cSharpCipher = '90iAiA80rSiyEoCAnLC9KNYt41koQKs2Lo5NzciyELkoZGne+BAv1ScMXSWETyAL',\r\n          nodeDecrpytedText;\r\n      nodeDecrpytedText = cryptLib.decrypt(cSharpCipher, cSharpKey, cSharpIv);\r\n      expect(nodeDecrpytedText).to.equal(cSharpPlainText);\r\n    });\r\n\r\n    it('decrypt 16 char iv and 32 char key generated by c#', function() {\r\n      var cSharpIv = 'HCHXjb_wIURjCV3G',\r\n          cSharpKey = 'b16920894899c7780b5fc7161560a412',\r\n          cSharpPlainText = 'C# text that\\'s going to be decrypted',\r\n          cSharpCipher = '0kv/H19UoAN21Et5jSNTM/yKQAaEPiB5Y6qugTQs3kvNuwMLBiOeFwMFnYr9KZBa',\r\n          nodeDecrpytedText;\r\n      nodeDecrpytedText = cryptLib.decrypt(cSharpCipher, cSharpKey, cSharpIv);\r\n      expect(nodeDecrpytedText).to.equal(cSharpPlainText);\r\n    });\r\n  });\r\n\r\n});\r\n\r\n"
  },
  {
    "path": "README.md",
    "content": "Cross platform 256bit AES encryption / decryption.\n========\nThis 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. \n\n<b>Platforms Supported:</b>\n\n1. iOS\n\n2. Android\n\n3. Windows (C#).\n\n4. Node.js\n\n<b>Features:</b>\n\n1. Cross platform support. Encryption-Decryption works across C#, iOS, Android and Node.js. \n\n2. 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.\n\n3.  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.\n\n<b>How to encrypt a string:</b>\n\nSee code samples for more details. You'll have to perform following steps:\n\n1. Generate Ramdom IV using the provided randomIV generator function.\n2. Select a secret key and hash it using the provided SHA-256 hash function.\n3. Encrypt your string using the hashed key and random IV. \n\n<b>How to decrypt a string:</b>\n\nSee code samples for more details. You'll have to perform following steps:\n\n1. Get the encrypted text and the randomIV used for encryption\n2. Decrypt the string using the provided decrypt function !\n"
  },
  {
    "path": "iOS/CryptLib.h",
    "content": "//\n//  CryptLib.h\n//\n\n#import <CommonCrypto/CommonDigest.h>\n#import <CommonCrypto/CommonCryptor.h>\n\n\n@interface StringEncryption : NSObject\n\n-  (NSData *)encrypt:(NSData *)plainText key:(NSString *)key iv:(NSString *)iv;\n-  (NSData *)decrypt:(NSData *)encryptedText key:(NSString *)key iv:(NSString *)iv;\n-  (NSData *)generateRandomIV:(size_t)length;\n-  (NSString *) md5:(NSString *) input;\n-  (NSString*) sha256:(NSString *)key length:(NSInteger) length;\n\n@end\n"
  },
  {
    "path": "iOS/CryptLib.m",
    "content": "\t/*****************************************************************\n\t * CrossPlatform CryptLib\n\t * \n\t * <p>\n\t * This cross platform CryptLib uses AES 256 for encryption. This library can\n\t * be used for encryptoion and de-cryption of string on iOS, Android and Windows\n\t * platform.<br/>\n\t * Features: <br/>\n\t * 1. 256 bit AES encryption\n\t * 2. Random IV generation. \n\t * 3. Provision for SHA256 hashing of key. \n\t * </p>\n\t * \n\t * @since 1.0\n\t * @author navneet\n\t *****************************************************************/\n// How to use :\n// //  1. Encryption:\n\n// NSString * _secret = @\"This the sample text has to be encrypted\"; // this is the text that you want to encrypt.\n\n// 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.\n\n// key = [[StringEncryption alloc] sha256:key length:32]; //this is very important, 32 bytes = 256 bit\n\n// 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\n\n// Now that we have input text, hashed key and random IV, we are all set for encryption:\n// NSData * encryptedData = [[StringEncryption alloc] encrypt:[secret dataUsingEncoding:NSUTF8StringEncoding] key:key iv:iv];\n\n// NSLog(@\"encrypted data:: %@\", [encryptedData  base64EncodingWithLineLength:0]); //print the encrypted text\n// Encryption = [plainText + secretKey + randomIV] = Cyphertext\n\n// // 2. Decryption\n// for decryption, you will have to use the same IV and key which was used for encryption.\n\n// encryptedData = [[StringEncryption alloc] decrypt:encryptedData  key:key iv:iv];\n// NSString * decryptedText = [[NSString alloc] initWithData:encryptedData encoding:NSUTF8StringEncoding];\n// NSLog(@\"decrypted data:: %@\", decryptedText); //print the decrypted text\n\n// For base64EncodingWithLineLength refer - https://github.com/jdg/MGTwitterEngine/blob/master/NSData%2BBase64.m\n\n\n#import \"CryptLib.h\"\n#import \"NSData+Base64.h\"\n\n\n@implementation StringEncryption\n\n- (NSData *)encrypt:(NSData *)plainText key:(NSString *)key  iv:(NSString *)iv {\n    char keyPointer[kCCKeySizeAES256+2],// room for terminator (unused) ref: https://devforums.apple.com/message/876053#876053\n    ivPointer[kCCBlockSizeAES128+2];\n    BOOL patchNeeded;\n    bzero(keyPointer, sizeof(keyPointer)); // fill with zeroes for padding\n    //key = [[StringEncryption alloc] md5:key];\n    patchNeeded= ([key length] > kCCKeySizeAES256+1);\n    if(patchNeeded)\n    {\n        NSLog(@\"Key length is longer %lu\", (unsigned long)[[[StringEncryption alloc] md5:key] length]);\n        key = [key substringToIndex:kCCKeySizeAES256]; // Ensure that the key isn't longer than what's needed (kCCKeySizeAES256)\n    }\n    \n    //NSLog(@\"md5 :%@\", key);\n    [key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding];\n    [iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding];\n    \n    if (patchNeeded) {\n        keyPointer[0] = '\\0';  // Previous iOS version than iOS7 set the first char to '\\0' if the key was longer than kCCKeySizeAES256\n    }\n    \n    NSUInteger dataLength = [plainText length];\n    \n    //see https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/CCryptorCreateFromData.3cc.html\n    // For block ciphers, the output size will always be less than or equal to the input size plus the size of one block.\n    size_t buffSize = dataLength + kCCBlockSizeAES128;\n    void *buff = malloc(buffSize);\n    \n    size_t numBytesEncrypted = 0;\n    //refer to http://www.opensource.apple.com/source/CommonCrypto/CommonCrypto-36064/CommonCrypto/CommonCryptor.h\n    //for details on this function\n    //Stateless, one-shot encrypt or decrypt operation.\n    CCCryptorStatus status = CCCrypt(kCCEncrypt, /* kCCEncrypt, etc. */\n                                     kCCAlgorithmAES128, /* kCCAlgorithmAES128, etc. */\n                                     kCCOptionPKCS7Padding, /* kCCOptionPKCS7Padding, etc. */\n                                     keyPointer, kCCKeySizeAES256, /* key and its length */\n                                     ivPointer, /* initialization vector - use random IV everytime */\n                                     [plainText bytes], [plainText length], /* input  */\n                                     buff, buffSize,/* data RETURNED here */\n                                     &numBytesEncrypted);\n    if (status == kCCSuccess) {\n        return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted];\n    }\n    \n    free(buff);\n    return nil;\n}\n\n\n-(NSData *)decrypt:(NSData *)encryptedText key:(NSString *)key iv:(NSString *)iv {\n    char keyPointer[kCCKeySizeAES256+2],// room for terminator (unused) ref: https://devforums.apple.com/message/876053#876053\n    ivPointer[kCCBlockSizeAES128+2];\n    BOOL patchNeeded;\n  \n    patchNeeded = ([key length] > kCCKeySizeAES256+1);\n    if(patchNeeded)\n    {\n        NSLog(@\"Key length is longer %lu\", (unsigned long)[[[StringEncryption alloc] md5:key] length]);\n        key = [key substringToIndex:kCCKeySizeAES256]; // Ensure that the key isn't longer than what's needed (kCCKeySizeAES256)\n    }\n\n    [key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding];\n    [iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding];\n\n    if (patchNeeded) {\n        keyPointer[0] = '\\0';  // Previous iOS version than iOS7 set the first char to '\\0' if the key was longer than kCCKeySizeAES256\n    }\n    \n    NSUInteger dataLength = [encryptedText length];\n    \n    //see https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/CCryptorCreateFromData.3cc.html\n    // For block ciphers, the output size will always be less than or equal to the input size plus the size of one block.\n    size_t buffSize = dataLength + kCCBlockSizeAES128;\n    \n    void *buff = malloc(buffSize);\n    \n    size_t numBytesEncrypted = 0;\n    //refer to http://www.opensource.apple.com/source/CommonCrypto/CommonCrypto-36064/CommonCrypto/CommonCryptor.h\n    //for details on this function\n    //Stateless, one-shot encrypt or decrypt operation.\n    CCCryptorStatus status = CCCrypt(kCCDecrypt,/* kCCEncrypt, etc. */\n                                     kCCAlgorithmAES128, /* kCCAlgorithmAES128, etc. */\n                                     kCCOptionPKCS7Padding, /* kCCOptionPKCS7Padding, etc. */\n                                     keyPointer, kCCKeySizeAES256,/* key and its length */\n                                     ivPointer, /* initialization vector - use same IV which was used for decryption */\n                                     [encryptedText bytes], [encryptedText length], //input\n                                     buff, buffSize,//output\n                                     &numBytesEncrypted);\n    if (status == kCCSuccess) {\n        return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted];\n    }\n    \n    free(buff);\n    return nil;\n}\n\n//this function is no longer used in encryption / decryption\n- (NSString *) md5:(NSString *) input\n{\n    const char *cStr = [input UTF8String];\n    unsigned char digest[16];\n    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call\n    \n    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];\n    \n    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)\n        [output appendFormat:@\"%02x\", digest[i]];\n    \n    return  output;\n    \n}\n\n//function to generate random string of given length. \n//random strings are used as IV\n- (NSData *)generateRandomIV:(size_t)length\n{\n    NSMutableData *data = [NSMutableData dataWithLength:length];\n    \n    int output = SecRandomCopyBytes(kSecRandomDefault,\n                                    length,\n                                    data.mutableBytes);\n    NSAssert(output == 0, @\"error generating random bytes: %d\",\n             errno);\n    \n    return data;\n}\n\n    /**\n\t * This function computes the SHA256 hash of input string\n\t * @param text input text whose SHA256 hash has to be computed\n\t * @param length length of the text to be returned\n\t * @return returns SHA256 hash of input text \n\t */\n- (NSString*) sha256:(NSString *)key length:(NSInteger) length{\n    const char *s=[key cStringUsingEncoding:NSASCIIStringEncoding];\n    NSData *keyData=[NSData dataWithBytes:s length:strlen(s)];\n    \n    uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0};\n    CC_SHA256(keyData.bytes, keyData.length, digest);\n    NSData *out=[NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];\n    NSString *hash=[out description];\n    hash = [hash stringByReplacingOccurrencesOfString:@\" \" withString:@\"\"];\n    hash = [hash stringByReplacingOccurrencesOfString:@\"<\" withString:@\"\"];\n    hash = [hash stringByReplacingOccurrencesOfString:@\">\" withString:@\"\"];\n    \n    if(length > [hash length])\n    {\n        return  hash;\n    }\n    else\n    {\n        return [hash substringToIndex:length];\n    }\n }\n\n@end\n"
  },
  {
    "path": "iOS/NSData+Base64.h",
    "content": "//\n//  NSData+Base64.h\n//  base64\n//\n//  Created by Matt Gallagher on 2009/06/03.\n//  Copyright 2009 Matt Gallagher. All rights reserved.\n//\n//  This software is provided 'as-is', without any express or implied\n//  warranty. In no event will the authors be held liable for any damages\n//  arising from the use of this software. Permission is granted to anyone to\n//  use this software for any purpose, including commercial applications, and to\n//  alter it and redistribute it freely, subject to the following restrictions:\n//\n//  1. The origin of this software must not be misrepresented; you must not\n//     claim that you wrote the original software. If you use this software\n//     in a product, an acknowledgment in the product documentation would be\n//     appreciated but is not required.\n//  2. Altered source versions must be plainly marked as such, and must not be\n//     misrepresented as being the original software.\n//  3. This notice may not be removed or altered from any source\n//     distribution.\n//\n\n#import <Foundation/Foundation.h>\n\nvoid *NewBase64Decode(\n\tconst char *inputBuffer,\n\tsize_t length,\n\tsize_t *outputLength);\n\nchar *NewBase64Encode(\n\tconst void *inputBuffer,\n\tsize_t length,\n\tbool separateLines,\n\tsize_t *outputLength);\n\n@interface NSData (Base64)\n\n+ (NSData *)dataFromBase64String:(NSString *)aString;\n- (NSString *)base64EncodedString;\n\n// added by Hiroshi Hashiguchi\n- (NSString *)base64EncodedStringWithSeparateLines:(BOOL)separateLines;\n\n@end"
  },
  {
    "path": "iOS/NSData+Base64.m",
    "content": "//\n//  NSData+Base64.m\n//\n// Derived from http://colloquy.info/project/browser/trunk/NSDataAdditions.h?rev=1576\n// Created by khammond on Mon Oct 29 2001.\n// Formatted by Timothy Hatcher on Sun Jul 4 2004.\n// Copyright (c) 2001 Kyle Hammond. All rights reserved.\n// Original development by Dave Winer.\n//\n\n#import \"NSData+Base64.h\"\n\n#import <Foundation/Foundation.h>\n\nstatic char encodingTable[64] = {\n\t\t'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',\n\t\t'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',\n\t\t'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',\n\t\t'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' };\n\n@implementation NSData (Base64)\n\n+ (NSData *) dataWithBase64EncodedString:(NSString *) string {\n\tNSData *result = [[NSData alloc] initWithBase64EncodedString:string];\n\treturn [result autorelease];\n}\n\n- (id) initWithBase64EncodedString:(NSString *) string {\n\tNSMutableData *mutableData = nil;\n\n\tif( string ) {\n\t\tunsigned long ixtext = 0;\n\t\tunsigned long lentext = 0;\n\t\tunsigned char ch = 0;\n\t\tunsigned char inbuf[3], outbuf[4];\n\t\tshort i = 0, ixinbuf = 0;\n\t\tBOOL flignore = NO;\n\t\tBOOL flendtext = NO;\n\t\tNSData *base64Data = nil;\n\t\tconst unsigned char *base64Bytes = nil;\n\n\t\t// Convert the string to ASCII data.\n\t\tbase64Data = [string dataUsingEncoding:NSASCIIStringEncoding];\n\t\tbase64Bytes = [base64Data bytes];\n\t\tmutableData = [NSMutableData dataWithCapacity:[base64Data length]];\n\t\tlentext = [base64Data length];\n\n\t\twhile( YES ) {\n\t\t\tif( ixtext >= lentext ) break;\n\t\t\tch = base64Bytes[ixtext++];\n\t\t\tflignore = NO;\n\n\t\t\tif( ( ch >= 'A' ) && ( ch <= 'Z' ) ) ch = ch - 'A';\n\t\t\telse if( ( ch >= 'a' ) && ( ch <= 'z' ) ) ch = ch - 'a' + 26;\n\t\t\telse if( ( ch >= '0' ) && ( ch <= '9' ) ) ch = ch - '0' + 52;\n\t\t\telse if( ch == '+' ) ch = 62;\n\t\t\telse if( ch == '=' ) flendtext = YES;\n\t\t\telse if( ch == '/' ) ch = 63;\n\t\t\telse flignore = YES; \n   \n\t\t\tif( ! flignore ) {\n\t\t\t\tshort ctcharsinbuf = 3;\n\t\t\t\tBOOL flbreak = NO;\n\n\t\t\t\tif( flendtext ) {\n\t\t\t\t\tif( ! ixinbuf ) break;\n\t\t\t\t\tif( ( ixinbuf == 1 ) || ( ixinbuf == 2 ) ) ctcharsinbuf = 1;\n\t\t\t\t\telse ctcharsinbuf = 2;\n\t\t\t\t\tixinbuf = 3;\n\t\t\t\t\tflbreak = YES;\n\t\t\t\t}\n\n\t\t\t\tinbuf [ixinbuf++] = ch;\n\n\t\t\t\tif( ixinbuf == 4 ) {\n\t\t\t\t\tixinbuf = 0;\n\t\t\t\t\toutbuf [0] = ( inbuf[0] << 2 ) | ( ( inbuf[1] & 0x30) >> 4 );\n\t\t\t\t\toutbuf [1] = ( ( inbuf[1] & 0x0F ) << 4 ) | ( ( inbuf[2] & 0x3C ) >> 2 );\n\t\t\t\t\toutbuf [2] = ( ( inbuf[2] & 0x03 ) << 6 ) | ( inbuf[3] & 0x3F );\n\n\t\t\t\t\tfor( i = 0; i < ctcharsinbuf; i++ ) \n\t\t\t\t\t\t[mutableData appendBytes:&outbuf[i] length:1];\n\t\t\t\t}\n\n\t\t\t\tif( flbreak )  break;\n\t\t\t}\n\t\t}\n\t}\n\n\tself = [self initWithData:mutableData];\n\treturn self;\n}\n\n- (NSString *) base64EncodingWithLineLength:(unsigned int) lineLength {\n\tconst unsigned char\t*bytes = [self bytes];\n\tNSMutableString *result = [NSMutableString stringWithCapacity:[self length]];\n\tunsigned long ixtext = 0;\n\tunsigned long lentext = [self length];\n\tlong ctremaining = 0;\n\tunsigned char inbuf[3], outbuf[4];\n\tshort i = 0;\n\tshort charsonline = 0, ctcopy = 0;\n\tunsigned long ix = 0;\n\n\twhile( YES ) {\n\t\tctremaining = lentext - ixtext;\n\t\tif( ctremaining <= 0 ) break;\n\n\t\tfor( i = 0; i < 3; i++ ) {\n\t\t\tix = ixtext + i;\n\t\t\tif( ix < lentext ) inbuf[i] = bytes[ix];\n\t\t\telse inbuf [i] = 0;\n\t\t}\n\n\t\toutbuf [0] = (inbuf [0] & 0xFC) >> 2;\n\t\toutbuf [1] = ((inbuf [0] & 0x03) << 4) | ((inbuf [1] & 0xF0) >> 4);\n\t\toutbuf [2] = ((inbuf [1] & 0x0F) << 2) | ((inbuf [2] & 0xC0) >> 6);\n\t\toutbuf [3] = inbuf [2] & 0x3F;\n\t\tctcopy = 4;\n\n\t\tswitch( ctremaining ) {\n\t\tcase 1: \n\t\t\tctcopy = 2; \n\t\t\tbreak;\n\t\tcase 2: \n\t\t\tctcopy = 3; \n\t\t\tbreak;\n\t\t}\n\n\t\tfor( i = 0; i < ctcopy; i++ )\n\t\t\t[result appendFormat:@\"%c\", encodingTable[outbuf[i]]];\n\n\t\tfor( i = ctcopy; i < 4; i++ )\n\t\t\t[result appendFormat:@\"%c\",'='];\n\n\t\tixtext += 3;\n\t\tcharsonline += 4;\n\n\t\tif( lineLength > 0 ) {\n\t\t\tif (charsonline >= lineLength) {\n\t\t\t\tcharsonline = 0;\n\t\t\t\t[result appendString:@\"\\n\"];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\n@end"
  }
]