-
Notifications
You must be signed in to change notification settings - Fork 10
/
widevine.go
96 lines (75 loc) · 2.13 KB
/
widevine.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
package widevine
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rsa"
"encoding/asn1"
"fmt"
"github.com/chmike/cmac-go"
"google.golang.org/protobuf/proto"
wvpb "github.com/iyear/gowidevine/widevinepb"
)
func ptr[T any](v T) *T {
return &v
}
func pkcs7Padding(data []byte, blockSize int) []byte {
padding := blockSize - (len(data) % blockSize)
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
func pkcs7Unpadding(data []byte, blockSize int) ([]byte, error) {
paddingLength := int(data[len(data)-1])
if paddingLength < 1 || paddingLength > blockSize {
return nil, fmt.Errorf("invalid padding length: %d", paddingLength)
}
return data[:len(data)-paddingLength], nil
}
func parsePublicKey(pubKey []byte) (*rsa.PublicKey, error) {
publicKey := &rsa.PublicKey{}
if _, err := asn1.Unmarshal(pubKey, publicKey); err != nil {
return nil, fmt.Errorf("unmarshal asn1: %w", err)
}
return publicKey, nil
}
func cmacAES(data, key []byte) []byte {
hash, err := cmac.New(aes.NewCipher, key)
if err != nil {
return nil
}
_, err = hash.Write(data)
if err != nil {
return nil
}
return hash.Sum(nil)
}
func decryptAES(key, iv, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
mode := cipher.NewCBCDecrypter(block, iv)
plaintext := make([]byte, len(ciphertext))
mode.CryptBlocks(plaintext, ciphertext)
unpaddedPlaintext, err := pkcs7Unpadding(plaintext, aes.BlockSize)
if err != nil {
return nil, err
}
return unpaddedPlaintext, nil
}
func ParseServiceCert(serviceCert []byte) (*wvpb.DrmCertificate, error) {
msg := wvpb.SignedMessage{}
err := proto.Unmarshal(serviceCert, &msg)
if err != nil {
return nil, fmt.Errorf("unmarshal signed message: %w", err)
}
signedCert := &wvpb.SignedDrmCertificate{}
if err = proto.Unmarshal(msg.Msg, signedCert); err != nil {
return nil, fmt.Errorf("unmarshal signed drm certificate: %w", err)
}
cert := &wvpb.DrmCertificate{}
if err = proto.Unmarshal(signedCert.DrmCertificate, cert); err != nil {
return nil, fmt.Errorf("unmarshal drm certificate: %w", err)
}
return cert, nil
}