ecies_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. // Copyright (c) 2013 Kyle Isom <kyle@tyrfingr.is>
  2. // Copyright (c) 2012 The Go Authors. All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. package ecies
  30. import (
  31. "bytes"
  32. "crypto/elliptic"
  33. "crypto/rand"
  34. "crypto/sha256"
  35. "encoding/hex"
  36. "flag"
  37. "fmt"
  38. "math/big"
  39. "testing"
  40. "github.com/ethereum/go-ethereum/crypto"
  41. )
  42. var dumpEnc bool
  43. func init() {
  44. flDump := flag.Bool("dump", false, "write encrypted test message to file")
  45. flag.Parse()
  46. dumpEnc = *flDump
  47. }
  48. // Ensure the KDF generates appropriately sized keys.
  49. func TestKDF(t *testing.T) {
  50. msg := []byte("Hello, world")
  51. h := sha256.New()
  52. k, err := concatKDF(h, msg, nil, 64)
  53. if err != nil {
  54. fmt.Println(err.Error())
  55. t.FailNow()
  56. }
  57. if len(k) != 64 {
  58. fmt.Printf("KDF: generated key is the wrong size (%d instead of 64\n", len(k))
  59. t.FailNow()
  60. }
  61. }
  62. var ErrBadSharedKeys = fmt.Errorf("ecies: shared keys don't match")
  63. // cmpParams compares a set of ECIES parameters. We assume, as per the
  64. // docs, that AES is the only supported symmetric encryption algorithm.
  65. func cmpParams(p1, p2 *ECIESParams) bool {
  66. return p1.hashAlgo == p2.hashAlgo &&
  67. p1.KeyLen == p2.KeyLen &&
  68. p1.BlockSize == p2.BlockSize
  69. }
  70. // cmpPublic returns true if the two public keys represent the same pojnt.
  71. func cmpPublic(pub1, pub2 PublicKey) bool {
  72. if pub1.X == nil || pub1.Y == nil {
  73. fmt.Println(ErrInvalidPublicKey.Error())
  74. return false
  75. }
  76. if pub2.X == nil || pub2.Y == nil {
  77. fmt.Println(ErrInvalidPublicKey.Error())
  78. return false
  79. }
  80. pub1Out := elliptic.Marshal(pub1.Curve, pub1.X, pub1.Y)
  81. pub2Out := elliptic.Marshal(pub2.Curve, pub2.X, pub2.Y)
  82. return bytes.Equal(pub1Out, pub2Out)
  83. }
  84. // cmpPrivate returns true if the two private keys are the same.
  85. func cmpPrivate(prv1, prv2 *PrivateKey) bool {
  86. if prv1 == nil || prv1.D == nil {
  87. return false
  88. } else if prv2 == nil || prv2.D == nil {
  89. return false
  90. } else if prv1.D.Cmp(prv2.D) != 0 {
  91. return false
  92. } else {
  93. return cmpPublic(prv1.PublicKey, prv2.PublicKey)
  94. }
  95. }
  96. // Validate the ECDH component.
  97. func TestSharedKey(t *testing.T) {
  98. prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
  99. if err != nil {
  100. fmt.Println(err.Error())
  101. t.FailNow()
  102. }
  103. skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2
  104. prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
  105. if err != nil {
  106. fmt.Println(err.Error())
  107. t.FailNow()
  108. }
  109. sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen)
  110. if err != nil {
  111. fmt.Println(err.Error())
  112. t.FailNow()
  113. }
  114. sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen)
  115. if err != nil {
  116. fmt.Println(err.Error())
  117. t.FailNow()
  118. }
  119. if !bytes.Equal(sk1, sk2) {
  120. fmt.Println(ErrBadSharedKeys.Error())
  121. t.FailNow()
  122. }
  123. }
  124. func TestSharedKeyPadding(t *testing.T) {
  125. // sanity checks
  126. prv0 := hexKey("1adf5c18167d96a1f9a0b1ef63be8aa27eaf6032c233b2b38f7850cf5b859fd9")
  127. prv1 := hexKey("0097a076fc7fcd9208240668e31c9abee952cbb6e375d1b8febc7499d6e16f1a")
  128. x0, _ := new(big.Int).SetString("1a8ed022ff7aec59dc1b440446bdda5ff6bcb3509a8b109077282b361efffbd8", 16)
  129. x1, _ := new(big.Int).SetString("6ab3ac374251f638d0abb3ef596d1dc67955b507c104e5f2009724812dc027b8", 16)
  130. y0, _ := new(big.Int).SetString("e040bd480b1deccc3bc40bd5b1fdcb7bfd352500b477cb9471366dbd4493f923", 16)
  131. y1, _ := new(big.Int).SetString("8ad915f2b503a8be6facab6588731fefeb584fd2dfa9a77a5e0bba1ec439e4fa", 16)
  132. if prv0.PublicKey.X.Cmp(x0) != 0 {
  133. t.Errorf("mismatched prv0.X:\nhave: %x\nwant: %x\n", prv0.PublicKey.X.Bytes(), x0.Bytes())
  134. }
  135. if prv0.PublicKey.Y.Cmp(y0) != 0 {
  136. t.Errorf("mismatched prv0.Y:\nhave: %x\nwant: %x\n", prv0.PublicKey.Y.Bytes(), y0.Bytes())
  137. }
  138. if prv1.PublicKey.X.Cmp(x1) != 0 {
  139. t.Errorf("mismatched prv1.X:\nhave: %x\nwant: %x\n", prv1.PublicKey.X.Bytes(), x1.Bytes())
  140. }
  141. if prv1.PublicKey.Y.Cmp(y1) != 0 {
  142. t.Errorf("mismatched prv1.Y:\nhave: %x\nwant: %x\n", prv1.PublicKey.Y.Bytes(), y1.Bytes())
  143. }
  144. // test shared secret generation
  145. sk1, err := prv0.GenerateShared(&prv1.PublicKey, 16, 16)
  146. if err != nil {
  147. fmt.Println(err.Error())
  148. }
  149. sk2, err := prv1.GenerateShared(&prv0.PublicKey, 16, 16)
  150. if err != nil {
  151. t.Fatal(err.Error())
  152. }
  153. if !bytes.Equal(sk1, sk2) {
  154. t.Fatal(ErrBadSharedKeys.Error())
  155. }
  156. }
  157. // Verify that the key generation code fails when too much key data is
  158. // requested.
  159. func TestTooBigSharedKey(t *testing.T) {
  160. prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
  161. if err != nil {
  162. fmt.Println(err.Error())
  163. t.FailNow()
  164. }
  165. prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
  166. if err != nil {
  167. fmt.Println(err.Error())
  168. t.FailNow()
  169. }
  170. _, err = prv1.GenerateShared(&prv2.PublicKey, 32, 32)
  171. if err != ErrSharedKeyTooBig {
  172. fmt.Println("ecdh: shared key should be too large for curve")
  173. t.FailNow()
  174. }
  175. _, err = prv2.GenerateShared(&prv1.PublicKey, 32, 32)
  176. if err != ErrSharedKeyTooBig {
  177. fmt.Println("ecdh: shared key should be too large for curve")
  178. t.FailNow()
  179. }
  180. }
  181. // Benchmark the generation of P256 keys.
  182. func BenchmarkGenerateKeyP256(b *testing.B) {
  183. for i := 0; i < b.N; i++ {
  184. if _, err := GenerateKey(rand.Reader, elliptic.P256(), nil); err != nil {
  185. fmt.Println(err.Error())
  186. b.FailNow()
  187. }
  188. }
  189. }
  190. // Benchmark the generation of P256 shared keys.
  191. func BenchmarkGenSharedKeyP256(b *testing.B) {
  192. prv, err := GenerateKey(rand.Reader, elliptic.P256(), nil)
  193. if err != nil {
  194. fmt.Println(err.Error())
  195. b.FailNow()
  196. }
  197. b.ResetTimer()
  198. for i := 0; i < b.N; i++ {
  199. _, err := prv.GenerateShared(&prv.PublicKey, 16, 16)
  200. if err != nil {
  201. fmt.Println(err.Error())
  202. b.FailNow()
  203. }
  204. }
  205. }
  206. // Benchmark the generation of S256 shared keys.
  207. func BenchmarkGenSharedKeyS256(b *testing.B) {
  208. prv, err := GenerateKey(rand.Reader, crypto.S256(), nil)
  209. if err != nil {
  210. fmt.Println(err.Error())
  211. b.FailNow()
  212. }
  213. b.ResetTimer()
  214. for i := 0; i < b.N; i++ {
  215. _, err := prv.GenerateShared(&prv.PublicKey, 16, 16)
  216. if err != nil {
  217. fmt.Println(err.Error())
  218. b.FailNow()
  219. }
  220. }
  221. }
  222. // Verify that an encrypted message can be successfully decrypted.
  223. func TestEncryptDecrypt(t *testing.T) {
  224. prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
  225. if err != nil {
  226. fmt.Println(err.Error())
  227. t.FailNow()
  228. }
  229. prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
  230. if err != nil {
  231. fmt.Println(err.Error())
  232. t.FailNow()
  233. }
  234. message := []byte("Hello, world.")
  235. ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil)
  236. if err != nil {
  237. fmt.Println(err.Error())
  238. t.FailNow()
  239. }
  240. pt, err := prv2.Decrypt(ct, nil, nil)
  241. if err != nil {
  242. fmt.Println(err.Error())
  243. t.FailNow()
  244. }
  245. if !bytes.Equal(pt, message) {
  246. fmt.Println("ecies: plaintext doesn't match message")
  247. t.FailNow()
  248. }
  249. _, err = prv1.Decrypt(ct, nil, nil)
  250. if err == nil {
  251. fmt.Println("ecies: encryption should not have succeeded")
  252. t.FailNow()
  253. }
  254. }
  255. func TestDecryptShared2(t *testing.T) {
  256. prv, err := GenerateKey(rand.Reader, DefaultCurve, nil)
  257. if err != nil {
  258. t.Fatal(err)
  259. }
  260. message := []byte("Hello, world.")
  261. shared2 := []byte("shared data 2")
  262. ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, shared2)
  263. if err != nil {
  264. t.Fatal(err)
  265. }
  266. // Check that decrypting with correct shared data works.
  267. pt, err := prv.Decrypt(ct, nil, shared2)
  268. if err != nil {
  269. t.Fatal(err)
  270. }
  271. if !bytes.Equal(pt, message) {
  272. t.Fatal("ecies: plaintext doesn't match message")
  273. }
  274. // Decrypting without shared data or incorrect shared data fails.
  275. if _, err = prv.Decrypt(ct, nil, nil); err == nil {
  276. t.Fatal("ecies: decrypting without shared data didn't fail")
  277. }
  278. if _, err = prv.Decrypt(ct, nil, []byte("garbage")); err == nil {
  279. t.Fatal("ecies: decrypting with incorrect shared data didn't fail")
  280. }
  281. }
  282. type testCase struct {
  283. Curve elliptic.Curve
  284. Name string
  285. Expected *ECIESParams
  286. }
  287. var testCases = []testCase{
  288. {
  289. Curve: elliptic.P256(),
  290. Name: "P256",
  291. Expected: ECIES_AES128_SHA256,
  292. },
  293. {
  294. Curve: elliptic.P384(),
  295. Name: "P384",
  296. Expected: ECIES_AES256_SHA384,
  297. },
  298. {
  299. Curve: elliptic.P521(),
  300. Name: "P521",
  301. Expected: ECIES_AES256_SHA512,
  302. },
  303. }
  304. // Test parameter selection for each curve, and that P224 fails automatic
  305. // parameter selection (see README for a discussion of P224). Ensures that
  306. // selecting a set of parameters automatically for the given curve works.
  307. func TestParamSelection(t *testing.T) {
  308. for _, c := range testCases {
  309. testParamSelection(t, c)
  310. }
  311. }
  312. func testParamSelection(t *testing.T, c testCase) {
  313. params := ParamsFromCurve(c.Curve)
  314. if params == nil && c.Expected != nil {
  315. fmt.Printf("%s (%s)\n", ErrInvalidParams.Error(), c.Name)
  316. t.FailNow()
  317. } else if params != nil && !cmpParams(params, c.Expected) {
  318. fmt.Printf("ecies: parameters should be invalid (%s)\n",
  319. c.Name)
  320. t.FailNow()
  321. }
  322. prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
  323. if err != nil {
  324. fmt.Printf("%s (%s)\n", err.Error(), c.Name)
  325. t.FailNow()
  326. }
  327. prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
  328. if err != nil {
  329. fmt.Printf("%s (%s)\n", err.Error(), c.Name)
  330. t.FailNow()
  331. }
  332. message := []byte("Hello, world.")
  333. ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil)
  334. if err != nil {
  335. fmt.Printf("%s (%s)\n", err.Error(), c.Name)
  336. t.FailNow()
  337. }
  338. pt, err := prv2.Decrypt(ct, nil, nil)
  339. if err != nil {
  340. fmt.Printf("%s (%s)\n", err.Error(), c.Name)
  341. t.FailNow()
  342. }
  343. if !bytes.Equal(pt, message) {
  344. fmt.Printf("ecies: plaintext doesn't match message (%s)\n",
  345. c.Name)
  346. t.FailNow()
  347. }
  348. _, err = prv1.Decrypt(ct, nil, nil)
  349. if err == nil {
  350. fmt.Printf("ecies: encryption should not have succeeded (%s)\n",
  351. c.Name)
  352. t.FailNow()
  353. }
  354. }
  355. // Ensure that the basic public key validation in the decryption operation
  356. // works.
  357. func TestBasicKeyValidation(t *testing.T) {
  358. badBytes := []byte{0, 1, 5, 6, 7, 8, 9}
  359. prv, err := GenerateKey(rand.Reader, DefaultCurve, nil)
  360. if err != nil {
  361. fmt.Println(err.Error())
  362. t.FailNow()
  363. }
  364. message := []byte("Hello, world.")
  365. ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, nil)
  366. if err != nil {
  367. fmt.Println(err.Error())
  368. t.FailNow()
  369. }
  370. for _, b := range badBytes {
  371. ct[0] = b
  372. _, err := prv.Decrypt(ct, nil, nil)
  373. if err != ErrInvalidPublicKey {
  374. fmt.Println("ecies: validated an invalid key")
  375. t.FailNow()
  376. }
  377. }
  378. }
  379. func TestBox(t *testing.T) {
  380. prv1 := hexKey("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f")
  381. prv2 := hexKey("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a")
  382. pub2 := &prv2.PublicKey
  383. message := []byte("Hello, world.")
  384. ct, err := Encrypt(rand.Reader, pub2, message, nil, nil)
  385. if err != nil {
  386. t.Fatal(err)
  387. }
  388. pt, err := prv2.Decrypt(ct, nil, nil)
  389. if err != nil {
  390. t.Fatal(err)
  391. }
  392. if !bytes.Equal(pt, message) {
  393. t.Fatal("ecies: plaintext doesn't match message")
  394. }
  395. if _, err = prv1.Decrypt(ct, nil, nil); err == nil {
  396. t.Fatal("ecies: encryption should not have succeeded")
  397. }
  398. }
  399. // Verify GenerateShared against static values - useful when
  400. // debugging changes in underlying libs
  401. func TestSharedKeyStatic(t *testing.T) {
  402. prv1 := hexKey("7ebbc6a8358bc76dd73ebc557056702c8cfc34e5cfcd90eb83af0347575fd2ad")
  403. prv2 := hexKey("6a3d6396903245bba5837752b9e0348874e72db0c4e11e9c485a81b4ea4353b9")
  404. skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2
  405. sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen)
  406. if err != nil {
  407. fmt.Println(err.Error())
  408. t.FailNow()
  409. }
  410. sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen)
  411. if err != nil {
  412. fmt.Println(err.Error())
  413. t.FailNow()
  414. }
  415. if !bytes.Equal(sk1, sk2) {
  416. fmt.Println(ErrBadSharedKeys.Error())
  417. t.FailNow()
  418. }
  419. sk, _ := hex.DecodeString("167ccc13ac5e8a26b131c3446030c60fbfac6aa8e31149d0869f93626a4cdf62")
  420. if !bytes.Equal(sk1, sk) {
  421. t.Fatalf("shared secret mismatch: want: %x have: %x", sk, sk1)
  422. }
  423. }
  424. func hexKey(prv string) *PrivateKey {
  425. key, err := crypto.HexToECDSA(prv)
  426. if err != nil {
  427. panic(err)
  428. }
  429. return ImportECDSA(key)
  430. }