crypto.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var lookup = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 62, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
  3. 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  4. 21, 22, 23, 24, 25, 0, 0, 0, 0, 63, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
  5. 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
  6. ]
  7. function base64Decode (source, target) {
  8. var sourceLength = source.length
  9. var paddingLength = (source[sourceLength - 2] === '=' ? 2 : (source[sourceLength - 1] === '=' ? 1
  10. : 0))
  11. var tmp
  12. var byteIndex = 0
  13. var baseLength = (sourceLength - paddingLength) & 0xfffffffc
  14. for (var i = 0; i < baseLength; i += 4) {
  15. tmp = (lookup[source.charCodeAt(i)] << 18) |
  16. (lookup[source.charCodeAt(i + 1)] << 12) |
  17. (lookup[source.charCodeAt(i + 2)] << 6) |
  18. (lookup[source.charCodeAt(i + 3)])
  19. target[byteIndex++] = (tmp >> 16) & 0xFF
  20. target[byteIndex++] = (tmp >> 8) & 0xFF
  21. target[byteIndex++] = (tmp) & 0xFF
  22. }
  23. if (paddingLength === 1) {
  24. tmp = (lookup[source.charCodeAt(i)] << 10) |
  25. (lookup[source.charCodeAt(i + 1)] << 4) |
  26. (lookup[source.charCodeAt(i + 2)] >> 2)
  27. target[byteIndex++] = (tmp >> 8) & 0xFF
  28. target[byteIndex++] = tmp & 0xFF
  29. }
  30. if (paddingLength === 2) {
  31. tmp = (lookup[source.charCodeAt(i)] << 2) | (lookup[source.charCodeAt(i + 1)] >> 4)
  32. target[byteIndex++] = tmp & 0xFF
  33. }
  34. }
  35. export default {
  36. getRandomValues (arr) {
  37. if (!(
  38. arr instanceof Int8Array ||
  39. arr instanceof Uint8Array ||
  40. arr instanceof Int16Array ||
  41. arr instanceof Uint16Array ||
  42. arr instanceof Int32Array ||
  43. arr instanceof Uint32Array ||
  44. arr instanceof Uint8ClampedArray
  45. )) {
  46. throw new Error('Expected an integer array')
  47. }
  48. if (arr.byteLength > 65536) {
  49. throw new Error('Can only request a maximum of 65536 bytes')
  50. }
  51. var crypto = uni.requireNativePlugin('DCloud-Crypto')
  52. base64Decode(crypto.getRandomValues(arr.byteLength), new Uint8Array(arr.buffer, arr.byteOffset,
  53. arr.byteLength))
  54. return arr
  55. }
  56. }