Debian Codegraph @

cipher/ecdh_es.go

raw symbols SCIP
1 /*-
2 * Copyright 2014 Square Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package josecipher
18
19 import (
20 "crypto"
21 "crypto/ecdsa"
22 "encoding/binary"
23 )
24
25 // DeriveECDHES derives a shared encryption key using ECDH/ConcatKDF as described in JWE/JWA.
26 // It is an error to call this function with a private/public key that are not on the same
27 // curve. Callers must ensure that the keys are valid before calling this function. Output
28 // size may be at most 1<<16 bytes (64 KiB).
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 // algId, partyUInfo, partyVInfo inputs must be prefixed with the length
35 algID := lengthPrefixed([]byte(alg))
36 ptyUInfo := lengthPrefixed(apuData)
37 ptyVInfo := lengthPrefixed(apvData)
38
39 // suppPubInfo is the encoded length of the output size in bits
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 // Read on the KDF will never fail
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 }