forked from InfiniteLoopSpace/go_S-MIME
/
ecdh.go
242 lines (184 loc) · 6.08 KB
/
ecdh.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package protocol
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/binary"
"errors"
"math/big"
"github.com/bukodi/go_S-MIME/oid"
)
var errUnsupported = errors.New("Unsupported hash function")
// ECDHsharedSecret computes shared secret with ephemeral static ECDH
func ECDHsharedSecret(curve elliptic.Curve, priv []byte, pubX, pubY *big.Int) []byte {
x, _ := curve.ScalarMult(pubX, pubY, priv)
return x.Bytes()
}
// ANSIx963KDF implents ANSI X9.63 key derivation function
func ANSIx963KDF(sharedSecret, sharedInfo []byte, keyLen int, hash crypto.Hash) (key []byte, err error) {
ctr := make([]byte, 4)
ctr[3] = 0x01
if hash == 0 || !hash.Available() {
return nil, errUnsupported
}
h := hash.New()
for i := 0; i < keyLen/hash.Size()+1; i++ {
h.Reset()
h.Write(sharedSecret)
h.Write(ctr)
h.Write(sharedInfo)
key = append(key, h.Sum(nil)...)
// Increment counter
for i := len(ctr) - 1; i >= 0; i-- {
ctr[i]++
if ctr[i] != 0 {
break
}
}
}
return key[:keyLen], nil
}
func encryptKeyECDH(key []byte, recipient *x509.Certificate) (kari KeyAgreeRecipientInfo, err error) {
keyWrapAlgorithm := oid.KeyWrap{KeyWrapAlgorithm: oid.AES128Wrap}
keyEncryptionAlgorithm := oid.DHSinglePassstdDHsha256kdfscheme
hash := oid.KDFHashAlgorithm[keyEncryptionAlgorithm.String()]
kari.UKM = make([]byte, 8)
rand.Read(kari.UKM)
kari.Version = 3
var oriId OriginatorIdentifierOrKey
oriId.OriginatorKey.Algorithm = pkix.AlgorithmIdentifier{Algorithm: oid.ECPublicKey}
// check recipient key
if recipient.PublicKeyAlgorithm != x509.ECDSA {
err = errors.New("Recipient certficiate has wrong public key algorithm, expected ECDSA")
return
}
pubKey, ok := recipient.PublicKey.(*ecdsa.PublicKey)
if !ok {
err = errors.New("Can not parse public key of recipient")
return
}
// genrate ephemeral public key and key encryption key
priv, x, y, err := elliptic.GenerateKey(pubKey.Curve, rand.Reader)
if err != nil {
return
}
ephPubKey := elliptic.Marshal(pubKey.Curve, x, y)
oriId.OriginatorKey.PublicKey = asn1.BitString{Bytes: ephPubKey, BitLength: len(ephPubKey) * 8}
sharedSecret := ECDHsharedSecret(pubKey.Curve, priv, pubKey.X, pubKey.Y)
keyLenBigEnd := make([]byte, 4)
binary.BigEndian.PutUint32(keyLenBigEnd, uint32(keyWrapAlgorithm.KeyLen())*8)
sharedInfo := ECCCMSSharedInfo{KeyInfo: keyWrapAlgorithm.AlgorithmIdentifier(),
SuppPubInfo: keyLenBigEnd,
EntityUInfo: kari.UKM}
sharedInfoDER, err := asn1.Marshal(sharedInfo)
kek, err := ANSIx963KDF(sharedSecret, sharedInfoDER, keyWrapAlgorithm.KeyLen(), hash)
if err != nil {
return
}
// encrypt key
keyWrapAlgorithm.KEK = kek
encKey, err := keyWrapAlgorithm.Wrap(key)
if err != nil {
return
}
keyWrapAlgorithmIdentifier, err := asn1RawValue(keyWrapAlgorithm.AlgorithmIdentifier())
if err != nil {
return
}
kari.KeyEncryptionAlgorithm = pkix.AlgorithmIdentifier{Algorithm: keyEncryptionAlgorithm,
Parameters: keyWrapAlgorithmIdentifier}
ias, err := NewIssuerAndSerialNumber(recipient)
if err != nil {
return
}
var karID KeyAgreeRecipientIdentifier
karID.IAS = &ias
rawKarId, err := karID.Marshal()
if err != nil {
return
}
kari.RecipientEncryptedKeys = append(kari.RecipientEncryptedKeys, RecipientEncryptedKey{RawRID: rawKarId, EncryptedKey: encKey})
kari.RawOriginator, err = oriId.Marshal()
if err != nil {
return
}
return
}
// ECCCMSSharedInfo ECC-CMS-SharedInfo ::= SEQUENCE {
// keyInfo AlgorithmIdentifier,
// entityUInfo [0] EXPLICIT OCTET STRING OPTIONAL,
// suppPubInfo [2] EXPLICIT OCTET STRING }
type ECCCMSSharedInfo struct {
KeyInfo pkix.AlgorithmIdentifier
EntityUInfo []byte `asn1:"optional,explicit,tag:0"`
SuppPubInfo []byte `asn1:"explicit,tag:2"`
}
func (kari *KeyAgreeRecipientInfo) decryptKey(keyPair tls.Certificate) (key []byte, err error) {
// check for ec key
if kari.Version != 3 {
err = errors.New("Version not supported")
return
}
var oriIdOrKey OriginatorIdentifierOrKey
if err := oriIdOrKey.Unmarshal(kari.RawOriginator); err != nil {
return nil, err
}
if !oriIdOrKey.OriginatorKey.Algorithm.Algorithm.Equal(oid.ECPublicKey) {
err = errors.New("Orginator key algorithm not supported")
return
}
pubKey, ok := keyPair.Leaf.PublicKey.(*ecdsa.PublicKey)
if !ok {
err = errors.New("Can not parse public key of recipient")
return
}
x, y := elliptic.Unmarshal(pubKey.Curve, oriIdOrKey.OriginatorKey.PublicKey.Bytes)
// genrate ephemeral public key and key encryption key
priv := keyPair.PrivateKey.(*ecdsa.PrivateKey)
privateKeyBytes := keyPair.PrivateKey.(*ecdsa.PrivateKey).D.Bytes()
paddedPrivateKey := make([]byte, (priv.Curve.Params().N.BitLen()+7)/8)
copy(paddedPrivateKey[len(paddedPrivateKey)-len(privateKeyBytes):], privateKeyBytes)
sharedSecret := ECDHsharedSecret(pubKey.Curve, paddedPrivateKey, x, y)
hash, ok := oid.KDFHashAlgorithm[kari.KeyEncryptionAlgorithm.Algorithm.String()]
if !ok {
err = errors.New("Unsupported key derivation hash algorithm")
return
}
var keyWrapAlgorithmIdentifier pkix.AlgorithmIdentifier
asn1.Unmarshal(kari.KeyEncryptionAlgorithm.Parameters.FullBytes, &keyWrapAlgorithmIdentifier)
keyWrapAlgorithm := oid.KeyWrap{KeyWrapAlgorithm: keyWrapAlgorithmIdentifier.Algorithm}
//
keyLenBigEnd := make([]byte, 4)
binary.BigEndian.PutUint32(keyLenBigEnd, uint32(keyWrapAlgorithm.KeyLen())*8)
sharedInfo := ECCCMSSharedInfo{KeyInfo: keyWrapAlgorithmIdentifier,
SuppPubInfo: keyLenBigEnd,
EntityUInfo: kari.UKM}
sharedInfoDER, err := asn1.Marshal(sharedInfo)
kek, err := ANSIx963KDF(sharedSecret, sharedInfoDER, keyWrapAlgorithm.KeyLen(), hash)
if err != nil {
return
}
keyWrapAlgorithm.KEK = kek
// encrypt key
ias, err := NewIssuerAndSerialNumber(keyPair.Leaf)
if err != nil {
return
}
for _, rEncKey := range kari.RecipientEncryptedKeys {
var rId KeyAgreeRecipientIdentifier
if err = rId.Unmarshal(rEncKey.RawRID); err != nil {
return
}
if rId.IAS != nil && rId.IAS.Equal(ias) {
key, err = keyWrapAlgorithm.UnWrap(rEncKey.EncryptedKey)
return
}
}
err = ErrNoKeyFound
return
}