EncryptionKeyGenerator.as 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /*
  2. Copyright (c) 2009, Adobe Systems Incorporated
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are
  6. met:
  7. * Redistributions of source code must retain the above copyright notice,
  8. this list of conditions and the following disclaimer.
  9. * Redistributions in binary form must reproduce the above copyright
  10. notice, this list of conditions and the following disclaimer in the
  11. documentation and/or other materials provided with the distribution.
  12. * Neither the name of Adobe Systems Incorporated nor the names of its
  13. contributors may be used to endorse or promote products derived from
  14. this software without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  16. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  17. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  18. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  19. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  20. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  22. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  23. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  24. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. package com.adobe.air.crypto
  28. {
  29. import com.adobe.crypto.SHA256;
  30. import flash.data.EncryptedLocalStore;
  31. import flash.utils.ByteArray;
  32. /**
  33. * The EncryptionKeyGenerator class generates an encryption key value, such as you would use
  34. * to encrypt files or data. For example, the encryption key is suitable to use as
  35. * an encryption key for an encrypted AIR local SQL (SQLite) database.
  36. *
  37. * <p>This class uses techniques and algorithms that are designed for maximum
  38. * data privacy and security. Use this class to generate an encryption key if your
  39. * application requires data to be encrypted on a per-user level (in other words,
  40. * if only one user of the application should be able to access his or her data).
  41. * In some situations you may also want to use per-user encryption for data even
  42. * if the application design specifies that other users can access the data. For more
  43. * information, see
  44. * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS34990ABF-C893-47ec-B813-9C9D9587A398.html">Considerations for using encryption with a database</a>"
  45. * in the guide
  46. * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/">Developing Adobe AIR Applications with Flex</a>."</p>
  47. *
  48. * <p>The generated encryption key is based on a password that you provide. For any given
  49. * password, in the same AIR application
  50. * running in the same user account on the same machine, the encryption key result is
  51. * the same.</p>
  52. *
  53. * <p>To generate an encryption key from a password, use the <code>getEncryptionKey()</code>
  54. * method. To confirm that a password is a "strong" password before calling the
  55. * <code>getEncryptionKey()</code> method, use the <code>validateStrongPassword()</code>
  56. * method.</p>
  57. *
  58. * <p>In addition, the EncryptionKeyGenerator includes a utility constant,
  59. * <code>ENCRYPTED_DB_PASSWORD_ERROR_ID</code>. This constant matches the error ID of
  60. * the SQLError error that occurs when code that is attempting to open an encrypted database
  61. * provides the wrong encryption key.</p>
  62. *
  63. * <p>This class is designed to create an encryption key suitable for providing the highest
  64. * level of data privacy and security. In order to achieve that level of security, a few
  65. * security principles must be followed:</p>
  66. *
  67. * <ul>
  68. * <li>Your application should never store the user-entered password</li>
  69. * <li>Your application should never store the encryption key returned by the
  70. * <code>getEncryptionKey()</code> method.</li>
  71. * <li>Instead, each time the user runs the application and attempts to access the database,
  72. * your application code should call the <code>getEncryptionKey()</code> method to
  73. * regenerate the encryption key.</li>
  74. * </ul>
  75. *
  76. * <p>For more information about data security, and an explanation of the security techniques
  77. * used in the EncryptionKeyGenerator class, see
  78. * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS61068DCE-9499-4d40-82B8-B71CC35D832C.html">Example: Generating and using an encryption key</a>"
  79. * in the guide
  80. * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/">Developing Adobe AIR Applications with Flex</a>."</p>
  81. */
  82. public class EncryptionKeyGenerator
  83. {
  84. // ------- Constants -------
  85. /**
  86. * This constant matches the error ID (3138) of the SQLError error that occurs when
  87. * code that is attempting to open an encrypted database provides the wrong
  88. * encryption key.
  89. */
  90. public static const ENCRYPTED_DB_PASSWORD_ERROR_ID:uint = 3138;
  91. private static const STRONG_PASSWORD_PATTERN:RegExp = /(?=^.{8,32}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/;
  92. private static const SALT_ELS_KEY:String = "com.adobe.air.crypto::EncryptedDBSalt$$$";
  93. // ------- Constructor -------
  94. /**
  95. * Creates a new EncryptionKeyGenerator instance.
  96. */
  97. public function EncryptionKeyGenerator() {}
  98. // ------- Public methods -------
  99. /**
  100. * Checks a password and returns a value indicating whether the password is a "strong"
  101. * password. The criteria for a strong password are:
  102. *
  103. * <ul>
  104. * <li>Minimum 8 characters</li>
  105. * <li>Maxmium 32 characters</li>
  106. * <li>Contains at least one lowercase letter</li>
  107. * <li>Contains at least one uppercase letter</li>
  108. * <li>Contains at least one number or symbol character</li>
  109. * </ul>
  110. *
  111. * @param password The password to check
  112. *
  113. * @return A value indicating whether the password is a strong password (<code>true</code>)
  114. * or not (<code>false</code>).
  115. */
  116. public function validateStrongPassword(password:String):Boolean
  117. {
  118. if (password == null || password.length <= 0)
  119. {
  120. return false;
  121. }
  122. return STRONG_PASSWORD_PATTERN.test(password);
  123. }
  124. /**
  125. * Uses a password to generate a 16-byte encryption key. The return value is suitable
  126. * to use as an encryption key for an encrypted AIR local SQL (SQLite) database.
  127. *
  128. * <p>For any given
  129. * password, calling the <code>getEncryptionKey()</code> method from the same AIR application
  130. * running in the same user account on the same machine, the encryption key result is
  131. * the same.
  132. *
  133. * <p>This method is designed to create an encryption key suitable for providing the highest
  134. * level of data privacy and security. In order to achieve that level of security, your
  135. * application must follow several security principles:</p>
  136. *
  137. * <ul>
  138. * <li>Your application can never store the user-entered password</li>
  139. * <li>Your application can never store the encryption key returned by the
  140. * <code>getEncryptionKey()</code> method.</li>
  141. * <li>Instead, each time the user runs the application and attempts to access the database,
  142. * call the <code>getEncryptionKey()</code> method to regenerate the encryption key.</li>
  143. * </ul>
  144. *
  145. * <p>For more information about data security, and an explanation of the security techniques
  146. * used in the EncryptionKeyGenerator class, see
  147. * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS61068DCE-9499-4d40-82B8-B71CC35D832C.html">Example: Generating and using an encryption key</a>"
  148. * in the guide
  149. * "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/">Developing Adobe AIR Applications with Flex</a>."</p>
  150. *
  151. * @param password The password to use to generate the encryption key.
  152. * @param overrideSaltELSKey The EncryptionKeyGenerator creates and stores a random value
  153. * (known as a <i>salt</i>) as part of the process of
  154. * generating the encryption key. The first time an application
  155. * calls the <code>getEncryptionKey()</code> method, the salt
  156. * value is created and stored in the AIR application's encrypted
  157. * local store (ELS). From then on, the salt value is loaded from the
  158. * ELS.
  159. * <p>If you wish to provide a custom String ELS key for storing
  160. * the salt value, specify a value for the <code>overrideSaltELSKey</code>
  161. * parameter. If the parameter is <code>null</code> (the default)
  162. * a default key name is used.</p>
  163. *
  164. * @return The generated encryption key, a 16-byte ByteArray object.
  165. *
  166. * @throws ArgumentError If the specified password is not a "strong" password according to the
  167. * criteria explained in the <code>validateStrongPassword()</code>
  168. * method description
  169. *
  170. * @throws ArgumentError If a non-<code>null</code> value is specified for the <code>overrideSaltELSKey</code>
  171. * parameter, and the value is an empty String (<code>""</code>)
  172. */
  173. public function getEncryptionKey(password:String, overrideSaltELSKey:String=null):ByteArray
  174. {
  175. if (!validateStrongPassword(password))
  176. {
  177. throw new ArgumentError("The password must be a strong password. It must be 8-32 characters long. It must contain at least one uppercase letter, at least one lowercase letter, and at least one number or symbol.");
  178. }
  179. if (overrideSaltELSKey != null && overrideSaltELSKey.length <= 0)
  180. {
  181. throw new ArgumentError("If an overrideSaltELSKey parameter value is specified, it can't be an empty String.");
  182. }
  183. var concatenatedPassword:String = concatenatePassword(password);
  184. var saltKey:String;
  185. if (overrideSaltELSKey == null)
  186. {
  187. saltKey = SALT_ELS_KEY;
  188. }
  189. else
  190. {
  191. saltKey = overrideSaltELSKey;
  192. }
  193. var salt:ByteArray = EncryptedLocalStore.getItem(saltKey);
  194. if (salt == null)
  195. {
  196. salt = makeSalt();
  197. EncryptedLocalStore.setItem(saltKey, salt);
  198. }
  199. var unhashedKey:ByteArray = xorBytes(concatenatedPassword, salt);
  200. var hashedKey:String = SHA256.hashBytes(unhashedKey);
  201. var encryptionKey:ByteArray = generateEncryptionKey(hashedKey);
  202. return encryptionKey;
  203. }
  204. // ------- Creating encryption key -------
  205. private function concatenatePassword(pwd:String):String
  206. {
  207. var len:int = pwd.length;
  208. var targetLength:int = 32;
  209. if (len == targetLength)
  210. {
  211. return pwd;
  212. }
  213. var repetitions:int = Math.floor(targetLength / len);
  214. var excess:int = targetLength % len;
  215. var result:String = "";
  216. for (var i:uint = 0; i < repetitions; i++)
  217. {
  218. result += pwd;
  219. }
  220. result += pwd.substr(0, excess);
  221. return result;
  222. }
  223. private function makeSalt():ByteArray
  224. {
  225. var result:ByteArray = new ByteArray;
  226. for (var i:uint = 0; i < 8; i++)
  227. {
  228. result.writeUnsignedInt(Math.round(Math.random() * uint.MAX_VALUE));
  229. }
  230. return result;
  231. }
  232. private function xorBytes(passwordString:String, salt:ByteArray):ByteArray
  233. {
  234. var result:ByteArray = new ByteArray();
  235. for (var i:uint = 0; i < 32; i += 4)
  236. {
  237. // Extract 4 bytes from the password string and convert to a uint
  238. var o1:uint = passwordString.charCodeAt(i) << 24;
  239. o1 += passwordString.charCodeAt(i + 1) << 16;
  240. o1 += passwordString.charCodeAt(i + 2) << 8;
  241. o1 += passwordString.charCodeAt(i + 3);
  242. salt.position = i;
  243. var o2:uint = salt.readUnsignedInt();
  244. var xor:uint = o1 ^ o2;
  245. result.writeUnsignedInt(xor);
  246. }
  247. return result;
  248. }
  249. private function generateEncryptionKey(hash:String):ByteArray
  250. {
  251. var result:ByteArray = new ByteArray();
  252. // select a range of 128 bits (32 hex characters) from the hash
  253. // In this case, we'll use the bits starting from position 17
  254. for (var i:uint = 0; i < 32; i += 2)
  255. {
  256. var position:uint = i + 17;
  257. var hex:String = hash.substr(position, 2);
  258. var byte:int = parseInt(hex, 16);
  259. result.writeByte(byte);
  260. }
  261. return result;
  262. }
  263. }
  264. }