| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package josecipher |
| 18 |
|
| 19 |
import ( |
| 20 |
"crypto" |
| 21 |
"crypto/ecdsa" |
| 22 |
"encoding/binary" |
| 23 |
) |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
func DeriveECDHES(alg string, apuData, apvData []byte, priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey, size int) []byte { |
| 30 |
if size > 1<<16 { |
| 31 |
panic("ECDH-ES output size too large, must be less than or equal to 1<<16") |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
algID := lengthPrefixed([]byte(alg)) |
| 36 |
ptyUInfo := lengthPrefixed(apuData) |
| 37 |
ptyVInfo := lengthPrefixed(apvData) |
| 38 |
|
| 39 |
|
| 40 |
supPubInfo := make([]byte, 4) |
| 41 |
binary.BigEndian.PutUint32(supPubInfo, uint32(size)*8) |
| 42 |
|
| 43 |
if !priv.PublicKey.Curve.IsOnCurve(pub.X, pub.Y) { |
| 44 |
panic("public key not on same curve as private key") |
| 45 |
} |
| 46 |
|
| 47 |
z, _ := priv.PublicKey.Curve.ScalarMult(pub.X, pub.Y, priv.D.Bytes()) |
| 48 |
reader := NewConcatKDF(crypto.SHA256, z.Bytes(), algID, ptyUInfo, ptyVInfo, supPubInfo, []byte{}) |
| 49 |
|
| 50 |
key := make([]byte, size) |
| 51 |
|
| 52 |
|
| 53 |
_, _ = reader.Read(key) |
| 54 |
return key |
| 55 |
} |
| 56 |
|
| 57 |
func lengthPrefixed(data []byte) []byte { |
| 58 |
out := make([]byte, len(data)+4) |
| 59 |
binary.BigEndian.PutUint32(out, uint32(len(data))) |
| 60 |
copy(out[4:], data) |
| 61 |
return out |
| 62 |
} |