| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package ecdh |
| 6 |
|
| 7 |
import ( |
| 8 |
"crypto/aes" |
| 9 |
"crypto/ecdsa" |
| 10 |
"crypto/elliptic" |
| 11 |
"crypto/hmac" |
| 12 |
"crypto/rand" |
| 13 |
"crypto/sha1" |
| 14 |
"crypto/sha256" |
| 15 |
"errors" |
| 16 |
|
| 17 |
"github.com/cloudflare/redoctober/padding" |
| 18 |
"github.com/cloudflare/redoctober/symcrypt" |
| 19 |
) |
| 20 |
|
| 21 |
var Curve = elliptic.P256 |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
func Encrypt(pub *ecdsa.PublicKey, in []byte) (out []byte, err error) { |
| 26 |
ephemeral, err := ecdsa.GenerateKey(Curve(), rand.Reader) |
| 27 |
if err != nil { |
| 28 |
return |
| 29 |
} |
| 30 |
x, _ := pub.Curve.ScalarMult(pub.X, pub.Y, ephemeral.D.Bytes()) |
| 31 |
if x == nil { |
| 32 |
return nil, errors.New("Failed to generate encryption key") |
| 33 |
} |
| 34 |
shared := sha256.Sum256(x.Bytes()) |
| 35 |
iv, err := symcrypt.MakeRandom(16) |
| 36 |
if err != nil { |
| 37 |
return |
| 38 |
} |
| 39 |
|
| 40 |
paddedIn := padding.AddPadding(in) |
| 41 |
ct, err := symcrypt.EncryptCBC(paddedIn, iv, shared[:16]) |
| 42 |
if err != nil { |
| 43 |
return |
| 44 |
} |
| 45 |
|
| 46 |
ephPub := elliptic.Marshal(pub.Curve, ephemeral.PublicKey.X, ephemeral.PublicKey.Y) |
| 47 |
out = make([]byte, 1+len(ephPub)+16) |
| 48 |
out[0] = byte(len(ephPub)) |
| 49 |
copy(out[1:], ephPub) |
| 50 |
copy(out[1+len(ephPub):], iv) |
| 51 |
out = append(out, ct...) |
| 52 |
|
| 53 |
h := hmac.New(sha1.New, shared[16:]) |
| 54 |
h.Write(iv) |
| 55 |
h.Write(ct) |
| 56 |
out = h.Sum(out) |
| 57 |
return |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
func Decrypt(priv *ecdsa.PrivateKey, in []byte) (out []byte, err error) { |
| 64 |
ephLen := int(in[0]) |
| 65 |
ephPub := in[1 : 1+ephLen] |
| 66 |
ct := in[1+ephLen:] |
| 67 |
if len(ct) < (sha1.Size + aes.BlockSize) { |
| 68 |
return nil, errors.New("Invalid ciphertext") |
| 69 |
} |
| 70 |
|
| 71 |
x, y := elliptic.Unmarshal(Curve(), ephPub) |
| 72 |
ok := Curve().IsOnCurve(x, y) |
| 73 |
if x == nil || !ok { |
| 74 |
return nil, errors.New("Invalid public key") |
| 75 |
} |
| 76 |
|
| 77 |
x, _ = priv.Curve.ScalarMult(x, y, priv.D.Bytes()) |
| 78 |
if x == nil { |
| 79 |
return nil, errors.New("Failed to generate encryption key") |
| 80 |
} |
| 81 |
shared := sha256.Sum256(x.Bytes()) |
| 82 |
|
| 83 |
tagStart := len(ct) - sha1.Size |
| 84 |
h := hmac.New(sha1.New, shared[16:]) |
| 85 |
h.Write(ct[:tagStart]) |
| 86 |
mac := h.Sum(nil) |
| 87 |
if !hmac.Equal(mac, ct[tagStart:]) { |
| 88 |
return nil, errors.New("Invalid MAC") |
| 89 |
} |
| 90 |
|
| 91 |
paddedOut, err := symcrypt.DecryptCBC(ct[aes.BlockSize:tagStart], ct[:aes.BlockSize], shared[:16]) |
| 92 |
if err != nil { |
| 93 |
return |
| 94 |
} |
| 95 |
out, err = padding.RemovePadding(paddedOut) |
| 96 |
return |
| 97 |
} |