You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

275 lines
7.4 KiB

  1. /* Copyright (c) 2018, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. // convert_wycheproof.go converts Wycheproof test vectors into a format more
  15. // easily consumed by BoringSSL.
  16. package main
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "io"
  21. "io/ioutil"
  22. "os"
  23. "sort"
  24. "strings"
  25. )
  26. type wycheproofTest struct {
  27. Algorithm string `json:"algorithm"`
  28. GeneratorVersion string `json:"generatorVersion"`
  29. NumberOfTests int `json:"numberOfTests"`
  30. Notes map[string]string `json:"notes"`
  31. Header []string `json:"header"`
  32. // encoding/json does not support collecting unused keys, so we leave
  33. // everything past this point as generic.
  34. TestGroups []map[string]interface{} `json:"testGroups"`
  35. }
  36. func sortedKeys(m map[string]interface{}) []string {
  37. keys := make([]string, 0, len(m))
  38. for k, _ := range m {
  39. keys = append(keys, k)
  40. }
  41. sort.Strings(keys)
  42. return keys
  43. }
  44. func printAttribute(w io.Writer, key string, valueI interface{}, isInstruction bool) error {
  45. switch value := valueI.(type) {
  46. case float64:
  47. if float64(int(value)) != value {
  48. panic(key + "was not an integer.")
  49. }
  50. if isInstruction {
  51. if _, err := fmt.Fprintf(w, "[%s = %d]\n", key, int(value)); err != nil {
  52. return err
  53. }
  54. } else {
  55. if _, err := fmt.Fprintf(w, "%s = %d\n", key, int(value)); err != nil {
  56. return err
  57. }
  58. }
  59. case string:
  60. if strings.Contains(value, "\n") {
  61. panic(key + " contained a newline.")
  62. }
  63. if isInstruction {
  64. if _, err := fmt.Fprintf(w, "[%s = %s]\n", key, value); err != nil {
  65. return err
  66. }
  67. } else {
  68. if _, err := fmt.Fprintf(w, "%s = %s\n", key, value); err != nil {
  69. return err
  70. }
  71. }
  72. case map[string]interface{}:
  73. for _, k := range sortedKeys(value) {
  74. if err := printAttribute(w, key+"."+k, value[k], isInstruction); err != nil {
  75. return err
  76. }
  77. }
  78. default:
  79. panic(fmt.Sprintf("Unknown type for %q: %T", key, valueI))
  80. }
  81. return nil
  82. }
  83. func printComment(w io.Writer, in string) error {
  84. const width = 80 - 2
  85. lines := strings.Split(in, "\n")
  86. for _, line := range lines {
  87. for {
  88. if len(line) <= width {
  89. if _, err := fmt.Fprintf(w, "# %s\n", line); err != nil {
  90. return err
  91. }
  92. break
  93. }
  94. // Find the last space we can break at.
  95. n := strings.LastIndexByte(line[:width+1], ' ')
  96. if n < 0 {
  97. // The next word is too long. Wrap as soon as that word ends.
  98. n = strings.IndexByte(line[width+1:], ' ')
  99. if n < 0 {
  100. // This was the last word.
  101. if _, err := fmt.Fprintf(w, "# %s\n", line); err != nil {
  102. return nil
  103. }
  104. break
  105. }
  106. n += width + 1
  107. }
  108. if _, err := fmt.Fprintf(w, "# %s\n", line[:n]); err != nil {
  109. return err
  110. }
  111. line = line[n+1:] // Ignore the space.
  112. }
  113. }
  114. return nil
  115. }
  116. func isSupportedCurve(curve string) bool {
  117. switch curve {
  118. case "brainpoolP224r1", "brainpoolP224t1", "brainpoolP256r1", "brainpoolP256t1", "brainpoolP320r1", "brainpoolP320t1", "brainpoolP384r1", "brainpoolP384t1", "brainpoolP512r1", "brainpoolP512t1", "secp256k1":
  119. return false
  120. case "edwards25519", "curve25519", "secp224r1", "secp256r1", "secp384r1", "secp521r1":
  121. return true
  122. default:
  123. panic("Unknown curve: " + curve)
  124. }
  125. }
  126. func convertWycheproof(f io.Writer, jsonPath string) error {
  127. jsonData, err := ioutil.ReadFile(jsonPath)
  128. if err != nil {
  129. return err
  130. }
  131. var w wycheproofTest
  132. if err := json.Unmarshal(jsonData, &w); err != nil {
  133. return err
  134. }
  135. if _, err := fmt.Fprintf(f, `# Imported from Wycheproof's %s.
  136. # This file is generated by convert_wycheproof.go. Do not edit by hand.
  137. #
  138. # Algorithm: %s
  139. # Generator version: %s
  140. `, jsonPath, w.Algorithm, w.GeneratorVersion); err != nil {
  141. return err
  142. }
  143. for _, group := range w.TestGroups {
  144. // Skip tests with unsupported curves. We filter these out at
  145. // conversion time to avoid unnecessarily inflating
  146. // crypto_test_data.cc.
  147. if curve, ok := group["curve"]; ok && !isSupportedCurve(curve.(string)) {
  148. continue
  149. }
  150. if keyI, ok := group["key"]; ok {
  151. if key, ok := keyI.(map[string]interface{}); ok {
  152. if curve, ok := key["curve"]; ok && !isSupportedCurve(curve.(string)) {
  153. continue
  154. }
  155. }
  156. }
  157. for _, k := range sortedKeys(group) {
  158. // Wycheproof files always include both keyPem and
  159. // keyDer. Skip keyPem as they contain newlines. We
  160. // process keyDer more easily.
  161. if k == "type" || k == "tests" || k == "keyPem" {
  162. continue
  163. }
  164. if err := printAttribute(f, k, group[k], true); err != nil {
  165. return err
  166. }
  167. }
  168. fmt.Fprintf(f, "\n")
  169. tests := group["tests"].([]interface{})
  170. for _, testI := range tests {
  171. test := testI.(map[string]interface{})
  172. // Skip tests with unsupported curves.
  173. if curve, ok := test["curve"]; ok && !isSupportedCurve(curve.(string)) {
  174. continue
  175. }
  176. if _, err := fmt.Fprintf(f, "# tcId = %d\n", int(test["tcId"].(float64))); err != nil {
  177. return err
  178. }
  179. if comment, ok := test["comment"]; ok && len(comment.(string)) != 0 {
  180. if err := printComment(f, comment.(string)); err != nil {
  181. return err
  182. }
  183. }
  184. for _, k := range sortedKeys(test) {
  185. if k == "comment" || k == "flags" || k == "tcId" {
  186. continue
  187. }
  188. if err := printAttribute(f, k, test[k], false); err != nil {
  189. return err
  190. }
  191. }
  192. if flags, ok := test["flags"]; ok {
  193. for _, flag := range flags.([]interface{}) {
  194. if note, ok := w.Notes[flag.(string)]; ok {
  195. if err := printComment(f, note); err != nil {
  196. return err
  197. }
  198. }
  199. }
  200. }
  201. if _, err := fmt.Fprintf(f, "\n"); err != nil {
  202. return err
  203. }
  204. }
  205. }
  206. return nil
  207. }
  208. var defaultInputs = []string{
  209. "aes_cbc_pkcs5_test.json",
  210. "aes_gcm_siv_test.json",
  211. "aes_gcm_test.json",
  212. "chacha20_poly1305_test.json",
  213. "dsa_test.json",
  214. "ecdh_test.json",
  215. "ecdsa_secp224r1_sha224_test.json",
  216. "ecdsa_secp224r1_sha256_test.json",
  217. "ecdsa_secp256r1_sha256_test.json",
  218. "ecdsa_secp384r1_sha384_test.json",
  219. "ecdsa_secp384r1_sha512_test.json",
  220. "ecdsa_secp521r1_sha512_test.json",
  221. "eddsa_test.json",
  222. "kw_test.json",
  223. "rsa_signature_test.json",
  224. "x25519_test.json",
  225. }
  226. func main() {
  227. switch len(os.Args) {
  228. case 1:
  229. for _, jsonPath := range defaultInputs {
  230. if !strings.HasSuffix(jsonPath, ".json") {
  231. panic(jsonPath)
  232. }
  233. txtPath := jsonPath[:len(jsonPath)-len(".json")] + ".txt"
  234. out, err := os.Create(txtPath)
  235. if err != nil {
  236. fmt.Fprintf(os.Stderr, "Error opening output %s: %s\n", txtPath, err)
  237. os.Exit(1)
  238. }
  239. defer out.Close()
  240. if err := convertWycheproof(out, jsonPath); err != nil {
  241. fmt.Fprintf(os.Stderr, "Error converting %s: %s\n", jsonPath, err)
  242. os.Exit(1)
  243. }
  244. }
  245. case 2:
  246. if err := convertWycheproof(os.Stdout, os.Args[1]); err != nil {
  247. fmt.Fprintf(os.Stderr, "Error converting %s: %s\n", os.Args[1], err)
  248. os.Exit(1)
  249. }
  250. default:
  251. fmt.Fprintf(os.Stderr, "Usage: %s [input JSON]\n", os.Args[0])
  252. os.Exit(1)
  253. }
  254. }