| 1 |
package x25519 |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"crypto/rand" |
| 6 |
"testing" |
| 7 |
) |
| 8 |
|
| 9 |
func TestGenerate(t *testing.T) { |
| 10 |
privateKey, err := GenerateKey(rand.Reader) |
| 11 |
if err != nil { |
| 12 |
t.Fatal(err) |
| 13 |
} |
| 14 |
if len(privateKey.Secret) != KeySize { |
| 15 |
t.Fatal("key has the wrong size") |
| 16 |
} |
| 17 |
if len(privateKey.PublicKey.Point) != KeySize { |
| 18 |
t.Fatal("key has the wrong size") |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
func TestValidate(t *testing.T) { |
| 23 |
privateKey, err := GenerateKey(rand.Reader) |
| 24 |
if err != nil { |
| 25 |
t.Fatal(err) |
| 26 |
} |
| 27 |
|
| 28 |
err = Validate(privateKey) |
| 29 |
if err != nil { |
| 30 |
t.Fatal(err) |
| 31 |
} |
| 32 |
privateKey.PublicKey.Point[0] = privateKey.PublicKey.Point[0] + byte(1) |
| 33 |
err = Validate(privateKey) |
| 34 |
if err == nil { |
| 35 |
t.Fatal("validation failed") |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
func TestEncryptDecrypt(t *testing.T) { |
| 40 |
sessionKey := []byte("session.........") |
| 41 |
privateKey, err := GenerateKey(rand.Reader) |
| 42 |
if err != nil { |
| 43 |
t.Fatal(err) |
| 44 |
} |
| 45 |
|
| 46 |
ephemeralPublic, ctxt, err := Encrypt(rand.Reader, &privateKey.PublicKey, sessionKey) |
| 47 |
if err != nil { |
| 48 |
t.Errorf("error encrypting: %s", err) |
| 49 |
} |
| 50 |
|
| 51 |
sessionKeyAfter, err := Decrypt(privateKey, ephemeralPublic, ctxt) |
| 52 |
if err != nil { |
| 53 |
t.Errorf("error decrypting: %s", err) |
| 54 |
} |
| 55 |
|
| 56 |
if !bytes.Equal(sessionKeyAfter, sessionKey) { |
| 57 |
t.Errorf("decryption failed, got: %x, want: %x", sessionKeyAfter, sessionKey) |
| 58 |
} |
| 59 |
} |