-
Notifications
You must be signed in to change notification settings - Fork 0
/
decrypt.go
63 lines (52 loc) · 1.38 KB
/
decrypt.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
// Copyright 2022 FishGoddess. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package cryptox
// Decrypter decrypts data from bytes, hex, and base64.
type Decrypter struct {
cipher Cipher
key []byte
mode DecryptMode
iv []byte
unPadding UnPadding
}
// NewDecrypter returns a new decrypter.
func NewDecrypter(cipher Cipher, key []byte, mode DecryptMode, iv []byte, unPadding UnPadding) Decrypter {
return Decrypter{
cipher: cipher,
key: key,
mode: mode,
iv: iv,
unPadding: unPadding,
}
}
// Decrypt decrypts data to bytes.
func (d Decrypter) Decrypt(crypted Bytes) (Bytes, error) {
block, err := d.cipher(d.key)
if err != nil {
return nil, err
}
crypted = crypted.Clone()
plain := crypted
err = d.mode.Crypt(block, d.iv, crypted, plain)
if err != nil {
return nil, err
}
return d.unPadding(plain, block.BlockSize())
}
// DecryptHex decrypts data in hex to bytes.
func (d Decrypter) DecryptHex(crypted string) (Bytes, error) {
decoded, err := ParseHex(crypted)
if err != nil {
return nil, err
}
return d.Decrypt(decoded)
}
// DecryptBase64 decrypts base64 in hex to bytes.
func (d Decrypter) DecryptBase64(crypted string) (Bytes, error) {
decoded, err := ParseBase64(crypted)
if err != nil {
return nil, err
}
return d.Decrypt(decoded)
}