This repository has been archived by the owner on Apr 21, 2023. It is now read-only.
/
alwaysencrypted.go
79 lines (64 loc) · 1.68 KB
/
alwaysencrypted.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
package alwaysencrypted
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/x509"
"encoding/binary"
"unicode/utf16"
)
type CEKV struct {
Version int
KeyPath string
Ciphertext []byte
SignedHash []byte
DataToSign []byte
Key []byte
}
func (c *CEKV) Verify(cert *x509.Certificate) bool {
sha256Sum := sha256.Sum256(c.DataToSign)
err := rsa.VerifyPKCS1v15(cert.PublicKey.(*rsa.PublicKey), crypto.SHA256, sha256Sum[:], c.SignedHash)
return err == nil
}
func (c *CEKV) Decrypt(private *rsa.PrivateKey) ([]byte, error) {
decryptedData, decryptErr := rsa.DecryptOAEP(sha1.New(), rand.Reader, private, c.Ciphertext, nil)
if decryptErr != nil {
return nil, decryptErr
}
return decryptedData, nil
}
func LoadCEKV(bytes []byte) CEKV {
idx := 0
version := int(bytes[idx])
idx++
keyPathLengthBytes := bytes[idx : idx+2]
keyPathLength := binary.LittleEndian.Uint16(keyPathLengthBytes)
idx += 2
cipherTextLengthBytes := bytes[idx : idx+2]
cipherTextLength := binary.LittleEndian.Uint16(cipherTextLengthBytes)
idx += 2
keyPathBytes := bytes[idx : idx+int(keyPathLength)]
idx += int(keyPathLength)
var uint16Bytes []uint16
for i := range keyPathBytes {
if i%2 == 0 {
continue
}
uint16Value := binary.LittleEndian.Uint16([]byte{keyPathBytes[i-1], keyPathBytes[i]})
uint16Bytes = append(uint16Bytes, uint16Value)
}
keyPath := string(utf16.Decode(uint16Bytes))
cipherText := bytes[idx : idx+int(cipherTextLength)]
idx += int(cipherTextLength)
dataToSign := bytes[0:idx]
signedHash := bytes[idx:]
return CEKV{
Version: version,
KeyPath: keyPath,
DataToSign: dataToSign,
Ciphertext: cipherText,
SignedHash: signedHash,
}
}