base64.nim 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2010 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements a base64 encoder and decoder.
  10. ##
  11. ## Unstable API.
  12. ##
  13. ## Base64 is an encoding and decoding technique used to convert binary
  14. ## data to an ASCII string format.
  15. ## Each Base64 digit represents exactly 6 bits of data. Three 8-bit
  16. ## bytes (i.e., a total of 24 bits) can therefore be represented by
  17. ## four 6-bit Base64 digits.
  18. ##
  19. ## Basic usage
  20. ## ===========
  21. ##
  22. ## Encoding data
  23. ## -------------
  24. ##
  25. ## .. code-block::nim
  26. ## import base64
  27. ## let encoded = encode("Hello World")
  28. ## assert encoded == "SGVsbG8gV29ybGQ="
  29. ##
  30. ## Apart from strings you can also encode lists of integers or characters:
  31. ##
  32. ## .. code-block::nim
  33. ## import base64
  34. ## let encodedInts = encode([1,2,3])
  35. ## assert encodedInts == "AQID"
  36. ## let encodedChars = encode(['h','e','y'])
  37. ## assert encodedChars == "aGV5"
  38. ##
  39. ##
  40. ## Decoding data
  41. ## -------------
  42. ##
  43. ## .. code-block::nim
  44. ## import base64
  45. ## let decoded = decode("SGVsbG8gV29ybGQ=")
  46. ## assert decoded == "Hello World"
  47. ##
  48. ## URL Safe Base64
  49. ## ---------------
  50. ##
  51. ## .. code-block::nim
  52. ## import base64
  53. ## doAssert encode("c\xf7>", safe = true) == "Y_c-"
  54. ## doAssert encode("c\xf7>", safe = false) == "Y/c+"
  55. ##
  56. ## See also
  57. ## ========
  58. ##
  59. ## * `hashes module<hashes.html>`_ for efficient computations of hash values for diverse Nim types
  60. ## * `md5 module<md5.html>`_ implements the MD5 checksum algorithm
  61. ## * `sha1 module<sha1.html>`_ implements a sha1 encoder and decoder
  62. template cbBase(a, b): untyped = [
  63. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  64. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  65. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  66. 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  67. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', a, b]
  68. let
  69. cb64 = cbBase('+', '/')
  70. cb64safe = cbBase('-', '_')
  71. const
  72. cb64VM = cbBase('+', '/')
  73. cb64safeVM = cbBase('-', '_')
  74. const
  75. invalidChar = 255
  76. template encodeSize(size: int): int = (size * 4 div 3) + 6
  77. template encodeInternal(s, alphabet: typed): untyped =
  78. ## encodes `s` into base64 representation.
  79. result.setLen(encodeSize(s.len))
  80. var
  81. inputIndex = 0
  82. outputIndex = 0
  83. inputEnds = s.len - s.len mod 3
  84. n: uint32
  85. b: uint32
  86. template inputByte(exp: untyped) =
  87. b = uint32(s[inputIndex])
  88. n = exp
  89. inc inputIndex
  90. template outputChar(x: typed) =
  91. result[outputIndex] = alphabet[x and 63]
  92. inc outputIndex
  93. template outputChar(c: char) =
  94. result[outputIndex] = c
  95. inc outputIndex
  96. while inputIndex != inputEnds:
  97. inputByte(b shl 16)
  98. inputByte(n or b shl 8)
  99. inputByte(n or b shl 0)
  100. outputChar(n shr 18)
  101. outputChar(n shr 12)
  102. outputChar(n shr 6)
  103. outputChar(n shr 0)
  104. var padding = s.len mod 3
  105. if padding == 1:
  106. inputByte(b shl 16)
  107. outputChar(n shr 18)
  108. outputChar(n shr 12)
  109. outputChar('=')
  110. outputChar('=')
  111. elif padding == 2:
  112. inputByte(b shl 16)
  113. inputByte(n or b shl 8)
  114. outputChar(n shr 18)
  115. outputChar(n shr 12)
  116. outputChar(n shr 6)
  117. outputChar('=')
  118. result.setLen(outputIndex)
  119. template encodeImpl() {.dirty.} =
  120. when nimVM:
  121. block:
  122. let lookupTableVM = if safe: cb64safeVM else: cb64VM
  123. encodeInternal(s, lookupTableVM)
  124. else:
  125. block:
  126. let lookupTable = if safe: unsafeAddr(cb64safe) else: unsafeAddr(cb64)
  127. encodeInternal(s, lookupTable)
  128. proc encode*[T: SomeInteger|char](s: openArray[T], safe = false): string =
  129. ## Encodes `s` into base64 representation.
  130. ##
  131. ## This procedure encodes an openarray (array or sequence) of either integers
  132. ## or characters.
  133. ##
  134. ## If ``safe`` is ``true`` then it will encode using the
  135. ## URL-Safe and Filesystem-safe standard alphabet characters,
  136. ## which substitutes ``-`` instead of ``+`` and ``_`` instead of ``/``.
  137. ## * https://en.wikipedia.org/wiki/Base64#URL_applications
  138. ## * https://tools.ietf.org/html/rfc4648#page-7
  139. ##
  140. ## **See also:**
  141. ## * `encode proc<#encode,string>`_ for encoding a string
  142. ## * `decode proc<#decode,string>`_ for decoding a string
  143. runnableExamples:
  144. assert encode(['n', 'i', 'm']) == "bmlt"
  145. assert encode(@['n', 'i', 'm']) == "bmlt"
  146. assert encode([1, 2, 3, 4, 5]) == "AQIDBAU="
  147. encodeImpl()
  148. proc encode*(s: string, safe = false): string =
  149. ## Encodes ``s`` into base64 representation.
  150. ##
  151. ## This procedure encodes a string.
  152. ##
  153. ## If ``safe`` is ``true`` then it will encode using the
  154. ## URL-Safe and Filesystem-safe standard alphabet characters,
  155. ## which substitutes ``-`` instead of ``+`` and ``_`` instead of ``/``.
  156. ## * https://en.wikipedia.org/wiki/Base64#URL_applications
  157. ## * https://tools.ietf.org/html/rfc4648#page-7
  158. ##
  159. ## **See also:**
  160. ## * `encode proc<#encode,openArray[T]>`_ for encoding an openarray
  161. ## * `decode proc<#decode,string>`_ for decoding a string
  162. runnableExamples:
  163. assert encode("Hello World") == "SGVsbG8gV29ybGQ="
  164. encodeImpl()
  165. proc encodeMime*(s: string, lineLen = 75, newLine = "\r\n"): string =
  166. ## Encodes ``s`` into base64 representation as lines.
  167. ## Used in email MIME format, use ``lineLen`` and ``newline``.
  168. ##
  169. ## This procedure encodes a string according to MIME spec.
  170. ##
  171. ## **See also:**
  172. ## * `encode proc<#encode,string>`_ for encoding a string
  173. ## * `decode proc<#decode,string>`_ for decoding a string
  174. runnableExamples:
  175. assert encodeMime("Hello World", 4, "\n") == "SGVs\nbG8g\nV29y\nbGQ="
  176. for i, c in encode(s):
  177. if i != 0 and (i mod lineLen == 0):
  178. result.add(newLine)
  179. result.add(c)
  180. proc initDecodeTable*(): array[256, char] =
  181. # computes a decode table at compile time
  182. for i in 0 ..< 256:
  183. let ch = char(i)
  184. var code = invalidChar
  185. if ch >= 'A' and ch <= 'Z': code = i - 0x00000041
  186. if ch >= 'a' and ch <= 'z': code = i - 0x00000047
  187. if ch >= '0' and ch <= '9': code = i + 0x00000004
  188. if ch == '+' or ch == '-': code = 0x0000003E
  189. if ch == '/' or ch == '_': code = 0x0000003F
  190. result[i] = char(code)
  191. const
  192. decodeTable = initDecodeTable()
  193. proc decode*(s: string): string =
  194. ## Decodes string ``s`` in base64 representation back into its original form.
  195. ## The initial whitespace is skipped.
  196. ##
  197. ## **See also:**
  198. ## * `encode proc<#encode,openArray[T]>`_ for encoding an openarray
  199. ## * `encode proc<#encode,string>`_ for encoding a string
  200. runnableExamples:
  201. assert decode("SGVsbG8gV29ybGQ=") == "Hello World"
  202. assert decode(" SGVsbG8gV29ybGQ=") == "Hello World"
  203. if s.len == 0: return
  204. proc decodeSize(size: int): int =
  205. return (size * 3 div 4) + 6
  206. template inputChar(x: untyped) =
  207. let x = int decodeTable[ord(s[inputIndex])]
  208. if x == invalidChar:
  209. raise newException(ValueError,
  210. "Invalid base64 format character `" & s[inputIndex] &
  211. "` (ord " & $s[inputIndex].ord & ") at location " & $inputIndex & ".")
  212. inc inputIndex
  213. template outputChar(x: untyped) =
  214. result[outputIndex] = char(x and 255)
  215. inc outputIndex
  216. # pre allocate output string once
  217. result.setLen(decodeSize(s.len))
  218. var
  219. inputIndex = 0
  220. outputIndex = 0
  221. inputLen = s.len
  222. inputEnds = 0
  223. # strip trailing characters
  224. while s[inputLen - 1] in {'\n', '\r', ' ', '='}:
  225. dec inputLen
  226. # hot loop: read 4 characters at at time
  227. inputEnds = inputLen - 4
  228. while inputIndex <= inputEnds:
  229. while s[inputIndex] in {'\n', '\r', ' '}:
  230. inc inputIndex
  231. inputChar(a)
  232. inputChar(b)
  233. inputChar(c)
  234. inputChar(d)
  235. outputChar(a shl 2 or b shr 4)
  236. outputChar(b shl 4 or c shr 2)
  237. outputChar(c shl 6 or d shr 0)
  238. # do the last 2 or 3 characters
  239. var leftLen = abs((inputIndex - inputLen) mod 4)
  240. if leftLen == 2:
  241. inputChar(a)
  242. inputChar(b)
  243. outputChar(a shl 2 or b shr 4)
  244. elif leftLen == 3:
  245. inputChar(a)
  246. inputChar(b)
  247. inputChar(c)
  248. outputChar(a shl 2 or b shr 4)
  249. outputChar(b shl 4 or c shr 2)
  250. result.setLen(outputIndex)