base64.nim 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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'u8,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. const
  58. cb64 = cbBase('+', '/')
  59. cb64safe = cbBase('-', '_')
  60. const
  61. invalidChar = 255
  62. template encodeSize(size: int): int = (size div 3 + size) + 6
  63. template encodeInternal(s, alphabet: typed): untyped =
  64. ## encodes `s` into base64 representation.
  65. result.setLen(encodeSize(s.len))
  66. let
  67. padding = s.len mod 3
  68. inputEnds = s.len - padding
  69. var
  70. inputIndex = 0
  71. outputIndex = 0
  72. n: uint32
  73. b: uint32
  74. template inputByte(exp: untyped) =
  75. b = uint32(s[inputIndex])
  76. n = exp
  77. inc inputIndex
  78. template outputChar(x: typed) =
  79. result[outputIndex] = alphabet[x and 63]
  80. inc outputIndex
  81. template outputChar(c: char) =
  82. result[outputIndex] = c
  83. inc outputIndex
  84. while inputIndex != inputEnds:
  85. inputByte(b shl 16)
  86. inputByte(n or b shl 8)
  87. inputByte(n or b shl 0)
  88. outputChar(n shr 18)
  89. outputChar(n shr 12)
  90. outputChar(n shr 6)
  91. outputChar(n shr 0)
  92. if padding == 1:
  93. inputByte(b shl 16)
  94. outputChar(n shr 18)
  95. outputChar(n shr 12)
  96. outputChar('=')
  97. outputChar('=')
  98. elif padding == 2:
  99. inputByte(b shl 16)
  100. inputByte(n or b shl 8)
  101. outputChar(n shr 18)
  102. outputChar(n shr 12)
  103. outputChar(n shr 6)
  104. outputChar('=')
  105. result.setLen(outputIndex)
  106. template encodeImpl() {.dirty.} =
  107. if safe:
  108. encodeInternal(s, cb64safe)
  109. else:
  110. encodeInternal(s, cb64)
  111. proc encode*[T: byte|char](s: openArray[T], safe = false): string =
  112. ## Encodes `s` into base64 representation.
  113. ##
  114. ## If `safe` is `true` then it will encode using the
  115. ## URL-Safe and Filesystem-safe standard alphabet characters,
  116. ## which substitutes `-` instead of `+` and `_` instead of `/`.
  117. ## * https://en.wikipedia.org/wiki/Base64#URL_applications
  118. ## * https://tools.ietf.org/html/rfc4648#page-7
  119. ##
  120. ## **See also:**
  121. ## * `decode proc<#decode,string>`_ for decoding a string
  122. runnableExamples:
  123. assert encode("Hello World") == "SGVsbG8gV29ybGQ="
  124. assert encode(['n', 'i', 'm']) == "bmlt"
  125. assert encode(@['n', 'i', 'm']) == "bmlt"
  126. assert encode([1'u8, 2, 3, 4, 5]) == "AQIDBAU="
  127. encodeImpl()
  128. proc encode*[T: SomeInteger and not byte](s: openArray[T], safe = false): string
  129. {.deprecated: "use `byte` or `char` instead".} =
  130. encodeImpl()
  131. proc encodeMime*(s: string, lineLen = 75.Positive, newLine = "\r\n",
  132. safe = false): string =
  133. ## Encodes `s` into base64 representation as lines.
  134. ## Used in email MIME format, use `lineLen` and `newline`.
  135. ##
  136. ## This procedure encodes a string according to MIME spec.
  137. ##
  138. ## If `safe` is `true` then it will encode using the
  139. ## URL-Safe and Filesystem-safe standard alphabet characters,
  140. ## which substitutes `-` instead of `+` and `_` instead of `/`.
  141. ## * https://en.wikipedia.org/wiki/Base64#URL_applications
  142. ## * https://tools.ietf.org/html/rfc4648#page-7
  143. ##
  144. ## **See also:**
  145. ## * `encode proc<#encode,openArray[T]>`_ for encoding an openArray
  146. ## * `decode proc<#decode,string>`_ for decoding a string
  147. runnableExamples:
  148. assert encodeMime("Hello World", 4, "\n") == "SGVs\nbG8g\nV29y\nbGQ="
  149. template cpy(l, src, idx) =
  150. b = l
  151. while i < b:
  152. result[i] = src[idx]
  153. inc i
  154. inc idx
  155. if s.len == 0: return
  156. let e = encode(s, safe)
  157. if e.len <= lineLen or newLine.len == 0:
  158. return e
  159. result = newString(e.len + newLine.len * ((e.len div lineLen) - int(e.len mod lineLen == 0)))
  160. var i, j, k, b: int
  161. let nd = e.len - lineLen
  162. while j < nd:
  163. cpy(i + lineLen, e, j)
  164. cpy(i + newLine.len, newLine, k)
  165. k = 0
  166. cpy(result.len, e, j)
  167. proc initDecodeTable*(): array[256, char] =
  168. # computes a decode table at compile time
  169. for i in 0 ..< 256:
  170. let ch = char(i)
  171. var code = invalidChar
  172. if ch >= 'A' and ch <= 'Z': code = i - 0x00000041
  173. if ch >= 'a' and ch <= 'z': code = i - 0x00000047
  174. if ch >= '0' and ch <= '9': code = i + 0x00000004
  175. if ch == '+' or ch == '-': code = 0x0000003E
  176. if ch == '/' or ch == '_': code = 0x0000003F
  177. result[i] = char(code)
  178. const
  179. decodeTable = initDecodeTable()
  180. proc decode*(s: string): string =
  181. ## Decodes string `s` in base64 representation back into its original form.
  182. ## The initial whitespace is skipped.
  183. ##
  184. ## **See also:**
  185. ## * `encode proc<#encode,openArray[T]>`_ for encoding an openarray
  186. runnableExamples:
  187. assert decode("SGVsbG8gV29ybGQ=") == "Hello World"
  188. assert decode(" SGVsbG8gV29ybGQ=") == "Hello World"
  189. if s.len == 0: return
  190. proc decodeSize(size: int): int =
  191. return (size * 3 div 4) + 6
  192. template inputChar(x: untyped) =
  193. let x = int decodeTable[ord(s[inputIndex])]
  194. if x == invalidChar:
  195. raise newException(ValueError,
  196. "Invalid base64 format character `" & s[inputIndex] &
  197. "` (ord " & $s[inputIndex].ord & ") at location " & $inputIndex & ".")
  198. inc inputIndex
  199. template outputChar(x: untyped) =
  200. result[outputIndex] = char(x and 255)
  201. inc outputIndex
  202. # pre allocate output string once
  203. result.setLen(decodeSize(s.len))
  204. var
  205. inputIndex = 0
  206. outputIndex = 0
  207. inputLen = s.len
  208. inputEnds = 0
  209. # strip trailing characters
  210. while inputLen > 0 and s[inputLen - 1] in {'\n', '\r', ' ', '='}:
  211. dec inputLen
  212. # hot loop: read 4 characters at at time
  213. inputEnds = inputLen - 4
  214. while inputIndex <= inputEnds:
  215. while s[inputIndex] in {'\n', '\r', ' '}:
  216. inc inputIndex
  217. inputChar(a)
  218. inputChar(b)
  219. inputChar(c)
  220. inputChar(d)
  221. outputChar(a shl 2 or b shr 4)
  222. outputChar(b shl 4 or c shr 2)
  223. outputChar(c shl 6 or d shr 0)
  224. # do the last 2 or 3 characters
  225. var leftLen = abs((inputIndex - inputLen) mod 4)
  226. if leftLen == 2:
  227. inputChar(a)
  228. inputChar(b)
  229. outputChar(a shl 2 or b shr 4)
  230. elif leftLen == 3:
  231. inputChar(a)
  232. inputChar(b)
  233. inputChar(c)
  234. outputChar(a shl 2 or b shr 4)
  235. outputChar(b shl 4 or c shr 2)
  236. result.setLen(outputIndex)