forked from AlexxIT/go2rtc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
72 lines (58 loc) · 1.32 KB
/
crypto.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
package webtorrent
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"encoding/base64"
"fmt"
"strconv"
"time"
)
type Cipher struct {
gcm cipher.AEAD
iv []byte
nonce []byte
}
func NewCipher(share, pwd, nonce string) (*Cipher, error) {
timestamp, err := strconv.ParseInt(nonce, 36, 64)
if err != nil {
return nil, err
}
delta := time.Duration(time.Now().UnixNano() - timestamp)
if delta < 0 {
delta = -delta
}
// protect from replay attack, but respect wrong timezone on server
if delta > 12*time.Hour {
return nil, fmt.Errorf("wrong timedelta %s", delta)
}
c := &Cipher{}
hash := sha256.New()
hash.Write([]byte(nonce + ":" + pwd))
key := hash.Sum(nil)
hash.Reset()
hash.Write([]byte(share + ":" + nonce))
c.iv = hash.Sum(nil)[:12]
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
c.gcm, err = cipher.NewGCM(block)
if err != nil {
return nil, err
}
c.nonce = []byte(nonce)
return c, nil
}
func (c *Cipher) Decrypt(ciphertext []byte) ([]byte, error) {
return c.gcm.Open(nil, c.iv, ciphertext, c.nonce)
}
func (c *Cipher) Encrypt(plaintext []byte) []byte {
return c.gcm.Seal(nil, c.iv, plaintext, c.nonce)
}
func InfoHash(share string) string {
hash := sha256.New()
hash.Write([]byte(share))
sum := hash.Sum(nil)
return base64.StdEncoding.EncodeToString(sum)
}