| 1 |
// Copyright 2011 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 |
|
| 5 |
package elgamal |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"crypto/rand" |
| 10 |
"math/big" |
| 11 |
"testing" |
| 12 |
) |
| 13 |
|
| 14 |
// This is the 1024-bit MODP group from RFC 5114, section 2.1: |
| 15 |
const primeHex = "B10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C69A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C013ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD7098488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708DF1FB2BC2E4A4371" |
| 16 |
|
| 17 |
const generatorHex = "A4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507FD6406CFF14266D31266FEA1E5C41564B777E690F5504F213160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28AD662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24855E6EEB22B3B2E5" |
| 18 |
|
| 19 |
func fromHex(hex string) *big.Int { |
| 20 |
n, ok := new(big.Int).SetString(hex, 16) |
| 21 |
if !ok { |
| 22 |
panic("failed to parse hex number") |
| 23 |
} |
| 24 |
return n |
| 25 |
} |
| 26 |
|
| 27 |
func TestEncryptDecrypt(t *testing.T) { |
| 28 |
priv := &PrivateKey{ |
| 29 |
PublicKey: PublicKey{ |
| 30 |
G: fromHex(generatorHex), |
| 31 |
P: fromHex(primeHex), |
| 32 |
}, |
| 33 |
X: fromHex("42"), |
| 34 |
} |
| 35 |
priv.Y = new(big.Int).Exp(priv.G, priv.X, priv.P) |
| 36 |
|
| 37 |
message := []byte("hello world") |
| 38 |
c1, c2, err := Encrypt(rand.Reader, &priv.PublicKey, message) |
| 39 |
if err != nil { |
| 40 |
t.Errorf("error encrypting: %s", err) |
| 41 |
} |
| 42 |
message2, err := Decrypt(priv, c1, c2) |
| 43 |
if err != nil { |
| 44 |
t.Errorf("error decrypting: %s", err) |
| 45 |
} |
| 46 |
if !bytes.Equal(message2, message) { |
| 47 |
t.Errorf("decryption failed, got: %x, want: %x", message2, message) |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
func TestDecryptBadKey(t *testing.T) { |
| 52 |
priv := &PrivateKey{ |
| 53 |
PublicKey: PublicKey{ |
| 54 |
G: fromHex(generatorHex), |
| 55 |
P: fromHex("2"), |
| 56 |
}, |
| 57 |
X: fromHex("42"), |
| 58 |
} |
| 59 |
priv.Y = new(big.Int).Exp(priv.G, priv.X, priv.P) |
| 60 |
c1, c2 := fromHex("8"), fromHex("8") |
| 61 |
if _, err := Decrypt(priv, c1, c2); err == nil { |
| 62 |
t.Errorf("unexpected success decrypting") |
| 63 |
} |
| 64 |
} |