base64.nim 8.1 KB

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