pkcs1v15_test.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package rsa
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/rand"
  9. "crypto/sha1"
  10. "crypto/sha256"
  11. "encoding/base64"
  12. "encoding/hex"
  13. "io"
  14. "math/big"
  15. "testing"
  16. "testing/quick"
  17. )
  18. func decodeBase64(in string) []byte {
  19. out := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
  20. n, err := base64.StdEncoding.Decode(out, []byte(in))
  21. if err != nil {
  22. return nil
  23. }
  24. return out[0:n]
  25. }
  26. type DecryptPKCS1v15Test struct {
  27. in, out string
  28. }
  29. // These test vectors were generated with `openssl rsautl -pkcs -encrypt`
  30. var decryptPKCS1v15Tests = []DecryptPKCS1v15Test{
  31. {
  32. "gIcUIoVkD6ATMBk/u/nlCZCCWRKdkfjCgFdo35VpRXLduiKXhNz1XupLLzTXAybEq15juc+EgY5o0DHv/nt3yg==",
  33. "x",
  34. },
  35. {
  36. "Y7TOCSqofGhkRb+jaVRLzK8xw2cSo1IVES19utzv6hwvx+M8kFsoWQm5DzBeJCZTCVDPkTpavUuEbgp8hnUGDw==",
  37. "testing.",
  38. },
  39. {
  40. "arReP9DJtEVyV2Dg3dDp4c/PSk1O6lxkoJ8HcFupoRorBZG+7+1fDAwT1olNddFnQMjmkb8vxwmNMoTAT/BFjQ==",
  41. "testing.\n",
  42. },
  43. {
  44. "WtaBXIoGC54+vH0NH0CHHE+dRDOsMc/6BrfFu2lEqcKL9+uDuWaf+Xj9mrbQCjjZcpQuX733zyok/jsnqe/Ftw==",
  45. "01234567890123456789012345678901234567890123456789012",
  46. },
  47. }
  48. func TestDecryptPKCS1v15(t *testing.T) {
  49. decryptionFuncs := []func([]byte) ([]byte, error){
  50. func(ciphertext []byte) (plaintext []byte, err error) {
  51. return DecryptPKCS1v15(nil, rsaPrivateKey, ciphertext)
  52. },
  53. func(ciphertext []byte) (plaintext []byte, err error) {
  54. return rsaPrivateKey.Decrypt(nil, ciphertext, nil)
  55. },
  56. }
  57. for _, decryptFunc := range decryptionFuncs {
  58. for i, test := range decryptPKCS1v15Tests {
  59. out, err := decryptFunc(decodeBase64(test.in))
  60. if err != nil {
  61. t.Errorf("#%d error decrypting", i)
  62. }
  63. want := []byte(test.out)
  64. if !bytes.Equal(out, want) {
  65. t.Errorf("#%d got:%#v want:%#v", i, out, want)
  66. }
  67. }
  68. }
  69. }
  70. func TestEncryptPKCS1v15(t *testing.T) {
  71. random := rand.Reader
  72. k := (rsaPrivateKey.N.BitLen() + 7) / 8
  73. tryEncryptDecrypt := func(in []byte, blind bool) bool {
  74. if len(in) > k-11 {
  75. in = in[0 : k-11]
  76. }
  77. ciphertext, err := EncryptPKCS1v15(random, &rsaPrivateKey.PublicKey, in)
  78. if err != nil {
  79. t.Errorf("error encrypting: %s", err)
  80. return false
  81. }
  82. var rand io.Reader
  83. if !blind {
  84. rand = nil
  85. } else {
  86. rand = random
  87. }
  88. plaintext, err := DecryptPKCS1v15(rand, rsaPrivateKey, ciphertext)
  89. if err != nil {
  90. t.Errorf("error decrypting: %s", err)
  91. return false
  92. }
  93. if !bytes.Equal(plaintext, in) {
  94. t.Errorf("output mismatch: %#v %#v", plaintext, in)
  95. return false
  96. }
  97. return true
  98. }
  99. config := new(quick.Config)
  100. if testing.Short() {
  101. config.MaxCount = 10
  102. }
  103. quick.Check(tryEncryptDecrypt, config)
  104. }
  105. // These test vectors were generated with `openssl rsautl -pkcs -encrypt`
  106. var decryptPKCS1v15SessionKeyTests = []DecryptPKCS1v15Test{
  107. {
  108. "e6ukkae6Gykq0fKzYwULpZehX+UPXYzMoB5mHQUDEiclRbOTqas4Y0E6nwns1BBpdvEJcilhl5zsox/6DtGsYg==",
  109. "1234",
  110. },
  111. {
  112. "Dtis4uk/q/LQGGqGk97P59K03hkCIVFMEFZRgVWOAAhxgYpCRG0MX2adptt92l67IqMki6iVQyyt0TtX3IdtEw==",
  113. "FAIL",
  114. },
  115. {
  116. "LIyFyCYCptPxrvTxpol8F3M7ZivlMsf53zs0vHRAv+rDIh2YsHS69ePMoPMe3TkOMZ3NupiL3takPxIs1sK+dw==",
  117. "abcd",
  118. },
  119. {
  120. "bafnobel46bKy76JzqU/RIVOH0uAYvzUtauKmIidKgM0sMlvobYVAVQPeUQ/oTGjbIZ1v/6Gyi5AO4DtHruGdw==",
  121. "FAIL",
  122. },
  123. }
  124. func TestEncryptPKCS1v15SessionKey(t *testing.T) {
  125. for i, test := range decryptPKCS1v15SessionKeyTests {
  126. key := []byte("FAIL")
  127. err := DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, decodeBase64(test.in), key)
  128. if err != nil {
  129. t.Errorf("#%d error decrypting", i)
  130. }
  131. want := []byte(test.out)
  132. if !bytes.Equal(key, want) {
  133. t.Errorf("#%d got:%#v want:%#v", i, key, want)
  134. }
  135. }
  136. }
  137. func TestEncryptPKCS1v15DecrypterSessionKey(t *testing.T) {
  138. for i, test := range decryptPKCS1v15SessionKeyTests {
  139. plaintext, err := rsaPrivateKey.Decrypt(rand.Reader, decodeBase64(test.in), &PKCS1v15DecryptOptions{SessionKeyLen: 4})
  140. if err != nil {
  141. t.Fatalf("#%d: error decrypting: %s", i, err)
  142. }
  143. if len(plaintext) != 4 {
  144. t.Fatalf("#%d: incorrect length plaintext: got %d, want 4", i, len(plaintext))
  145. }
  146. if test.out != "FAIL" && !bytes.Equal(plaintext, []byte(test.out)) {
  147. t.Errorf("#%d: incorrect plaintext: got %x, want %x", i, plaintext, test.out)
  148. }
  149. }
  150. }
  151. func TestNonZeroRandomBytes(t *testing.T) {
  152. random := rand.Reader
  153. b := make([]byte, 512)
  154. err := nonZeroRandomBytes(b, random)
  155. if err != nil {
  156. t.Errorf("returned error: %s", err)
  157. }
  158. for _, b := range b {
  159. if b == 0 {
  160. t.Errorf("Zero octet found")
  161. return
  162. }
  163. }
  164. }
  165. type signPKCS1v15Test struct {
  166. in, out string
  167. }
  168. // These vectors have been tested with
  169. // `openssl rsautl -verify -inkey pk -in signature | hexdump -C`
  170. var signPKCS1v15Tests = []signPKCS1v15Test{
  171. {"Test.\n", "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e336ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"},
  172. }
  173. func TestSignPKCS1v15(t *testing.T) {
  174. for i, test := range signPKCS1v15Tests {
  175. h := sha1.New()
  176. h.Write([]byte(test.in))
  177. digest := h.Sum(nil)
  178. s, err := SignPKCS1v15(nil, rsaPrivateKey, crypto.SHA1, digest)
  179. if err != nil {
  180. t.Errorf("#%d %s", i, err)
  181. }
  182. expected, _ := hex.DecodeString(test.out)
  183. if !bytes.Equal(s, expected) {
  184. t.Errorf("#%d got: %x want: %x", i, s, expected)
  185. }
  186. }
  187. }
  188. func TestVerifyPKCS1v15(t *testing.T) {
  189. for i, test := range signPKCS1v15Tests {
  190. h := sha1.New()
  191. h.Write([]byte(test.in))
  192. digest := h.Sum(nil)
  193. sig, _ := hex.DecodeString(test.out)
  194. err := VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.SHA1, digest, sig)
  195. if err != nil {
  196. t.Errorf("#%d %s", i, err)
  197. }
  198. }
  199. }
  200. func TestOverlongMessagePKCS1v15(t *testing.T) {
  201. ciphertext := decodeBase64("fjOVdirUzFoLlukv80dBllMLjXythIf22feqPrNo0YoIjzyzyoMFiLjAc/Y4krkeZ11XFThIrEvw\nkRiZcCq5ng==")
  202. _, err := DecryptPKCS1v15(nil, rsaPrivateKey, ciphertext)
  203. if err == nil {
  204. t.Error("RSA decrypted a message that was too long.")
  205. }
  206. }
  207. func TestUnpaddedSignature(t *testing.T) {
  208. msg := []byte("Thu Dec 19 18:06:16 EST 2013\n")
  209. // This base64 value was generated with:
  210. // % echo Thu Dec 19 18:06:16 EST 2013 > /tmp/msg
  211. // % openssl rsautl -sign -inkey key -out /tmp/sig -in /tmp/msg
  212. //
  213. // Where "key" contains the RSA private key given at the bottom of this
  214. // file.
  215. expectedSig := decodeBase64("pX4DR8azytjdQ1rtUiC040FjkepuQut5q2ZFX1pTjBrOVKNjgsCDyiJDGZTCNoh9qpXYbhl7iEym30BWWwuiZg==")
  216. sig, err := SignPKCS1v15(nil, rsaPrivateKey, crypto.Hash(0), msg)
  217. if err != nil {
  218. t.Fatalf("SignPKCS1v15 failed: %s", err)
  219. }
  220. if !bytes.Equal(sig, expectedSig) {
  221. t.Fatalf("signature is not expected value: got %x, want %x", sig, expectedSig)
  222. }
  223. if err := VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.Hash(0), msg, sig); err != nil {
  224. t.Fatalf("signature failed to verify: %s", err)
  225. }
  226. }
  227. func TestShortSessionKey(t *testing.T) {
  228. // This tests that attempting to decrypt a session key where the
  229. // ciphertext is too small doesn't run outside the array bounds.
  230. ciphertext, err := EncryptPKCS1v15(rand.Reader, &rsaPrivateKey.PublicKey, []byte{1})
  231. if err != nil {
  232. t.Fatalf("Failed to encrypt short message: %s", err)
  233. }
  234. var key [32]byte
  235. if err := DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, ciphertext, key[:]); err != nil {
  236. t.Fatalf("Failed to decrypt short message: %s", err)
  237. }
  238. for _, v := range key {
  239. if v != 0 {
  240. t.Fatal("key was modified when ciphertext was invalid")
  241. }
  242. }
  243. }
  244. // In order to generate new test vectors you'll need the PEM form of this key (and s/TESTING/PRIVATE/):
  245. // -----BEGIN RSA TESTING KEY-----
  246. // MIIBOgIBAAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0
  247. // fd7Ai2KW5ToIwzFofvJcS/STa6HA5gQenRUCAwEAAQJBAIq9amn00aS0h/CrjXqu
  248. // /ThglAXJmZhOMPVn4eiu7/ROixi9sex436MaVeMqSNf7Ex9a8fRNfWss7Sqd9eWu
  249. // RTUCIQDasvGASLqmjeffBNLTXV2A5g4t+kLVCpsEIZAycV5GswIhANEPLmax0ME/
  250. // EO+ZJ79TJKN5yiGBRsv5yvx5UiHxajEXAiAhAol5N4EUyq6I9w1rYdhPMGpLfk7A
  251. // IU2snfRJ6Nq2CQIgFrPsWRCkV+gOYcajD17rEqmuLrdIRexpg8N1DOSXoJ8CIGlS
  252. // tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V
  253. // -----END RSA TESTING KEY-----
  254. var rsaPrivateKey = &PrivateKey{
  255. PublicKey: PublicKey{
  256. N: fromBase10("9353930466774385905609975137998169297361893554149986716853295022578535724979677252958524466350471210367835187480748268864277464700638583474144061408845077"),
  257. E: 65537,
  258. },
  259. D: fromBase10("7266398431328116344057699379749222532279343923819063639497049039389899328538543087657733766554155839834519529439851673014800261285757759040931985506583861"),
  260. Primes: []*big.Int{
  261. fromBase10("98920366548084643601728869055592650835572950932266967461790948584315647051443"),
  262. fromBase10("94560208308847015747498523884063394671606671904944666360068158221458669711639"),
  263. },
  264. }
  265. func TestShortPKCS1v15Signature(t *testing.T) {
  266. pub := &PublicKey{
  267. E: 65537,
  268. N: fromBase10("8272693557323587081220342447407965471608219912416565371060697606400726784709760494166080686904546560026343451112103559482851304715739629410219358933351333"),
  269. }
  270. sig, err := hex.DecodeString("193a310d0dcf64094c6e3a00c8219b80ded70535473acff72c08e1222974bb24a93a535b1dc4c59fc0e65775df7ba2007dd20e9193f4c4025a18a7070aee93")
  271. if err != nil {
  272. t.Fatalf("failed to decode signature: %s", err)
  273. }
  274. h := sha256.Sum256([]byte("hello"))
  275. err = VerifyPKCS1v15(pub, crypto.SHA256, h[:], sig)
  276. if err == nil {
  277. t.Fatal("VerifyPKCS1v15 accepted a truncated signature")
  278. }
  279. }