base64.nim 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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>`_ implements the MD5 checksum algorithm
  50. ## * `sha1 module<sha1.html>`_ implements a sha1 encoder and decoder
  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, 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. result = newStringOfCap(encodeSize(s.len))
  166. for i, c in encode(s):
  167. if i != 0 and (i mod lineLen == 0):
  168. result.add(newLine)
  169. result.add(c)
  170. proc initDecodeTable*(): array[256, char] =
  171. # computes a decode table at compile time
  172. for i in 0 ..< 256:
  173. let ch = char(i)
  174. var code = invalidChar
  175. if ch >= 'A' and ch <= 'Z': code = i - 0x00000041
  176. if ch >= 'a' and ch <= 'z': code = i - 0x00000047
  177. if ch >= '0' and ch <= '9': code = i + 0x00000004
  178. if ch == '+' or ch == '-': code = 0x0000003E
  179. if ch == '/' or ch == '_': code = 0x0000003F
  180. result[i] = char(code)
  181. const
  182. decodeTable = initDecodeTable()
  183. proc decode*(s: string): string =
  184. ## Decodes string `s` in base64 representation back into its original form.
  185. ## The initial whitespace is skipped.
  186. ##
  187. ## **See also:**
  188. ## * `encode proc<#encode,openArray[T]>`_ for encoding an openarray
  189. ## * `encode proc<#encode,string>`_ for encoding a string
  190. runnableExamples:
  191. assert decode("SGVsbG8gV29ybGQ=") == "Hello World"
  192. assert decode(" SGVsbG8gV29ybGQ=") == "Hello World"
  193. if s.len == 0: return
  194. proc decodeSize(size: int): int =
  195. return (size * 3 div 4) + 6
  196. template inputChar(x: untyped) =
  197. let x = int decodeTable[ord(s[inputIndex])]
  198. if x == invalidChar:
  199. raise newException(ValueError,
  200. "Invalid base64 format character `" & s[inputIndex] &
  201. "` (ord " & $s[inputIndex].ord & ") at location " & $inputIndex & ".")
  202. inc inputIndex
  203. template outputChar(x: untyped) =
  204. result[outputIndex] = char(x and 255)
  205. inc outputIndex
  206. # pre allocate output string once
  207. result.setLen(decodeSize(s.len))
  208. var
  209. inputIndex = 0
  210. outputIndex = 0
  211. inputLen = s.len
  212. inputEnds = 0
  213. # strip trailing characters
  214. while s[inputLen - 1] in {'\n', '\r', ' ', '='}:
  215. dec inputLen
  216. # hot loop: read 4 characters at at time
  217. inputEnds = inputLen - 4
  218. while inputIndex <= inputEnds:
  219. while s[inputIndex] in {'\n', '\r', ' '}:
  220. inc inputIndex
  221. inputChar(a)
  222. inputChar(b)
  223. inputChar(c)
  224. inputChar(d)
  225. outputChar(a shl 2 or b shr 4)
  226. outputChar(b shl 4 or c shr 2)
  227. outputChar(c shl 6 or d shr 0)
  228. # do the last 2 or 3 characters
  229. var leftLen = abs((inputIndex - inputLen) mod 4)
  230. if leftLen == 2:
  231. inputChar(a)
  232. inputChar(b)
  233. outputChar(a shl 2 or b shr 4)
  234. elif leftLen == 3:
  235. inputChar(a)
  236. inputChar(b)
  237. inputChar(c)
  238. outputChar(a shl 2 or b shr 4)
  239. outputChar(b shl 4 or c shr 2)
  240. result.setLen(outputIndex)