forked from karlmcguire/ige
-
Notifications
You must be signed in to change notification settings - Fork 2
/
decrypt.go
60 lines (48 loc) · 1.36 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
package ige
import (
"crypto/cipher"
"github.com/go-faster/xor"
)
// NewIGEDecrypter returns an IGE cipher.BlockMode which decrypts using IGE and
// the given cipher.Block.
//
// Note: iv must contain two iv values for IGE (concatenated), otherwise this
// function will panic. See ErrInvalidIV for more information.
func NewIGEDecrypter(b cipher.Block, iv []byte) IGE {
if err := checkIV(b, iv); err != nil {
panic(err.Error())
}
return (*igeDecrypter)(newIGE(b, iv))
}
type igeDecrypter ige
func (i *igeDecrypter) BlockSize() int {
return i.block.BlockSize()
}
func (i *igeDecrypter) CryptBlocks(dst, src []byte) {
DecryptBlocks(i.block, i.iv, dst, src)
}
// DecryptBlocks is a simple shorthand for IGE decrypting.
// Note: unlike NewIGEDecrypter, DecryptBlocks does NOT COPY iv.
// So you must not modify passed iv.
func DecryptBlocks(block cipher.Block, iv, dst, src []byte) {
if err := checkIV(block, iv); err != nil {
panic(err.Error())
}
if len(src)%block.BlockSize() != 0 {
panic("src not full blocks")
}
if len(dst) < len(src) {
panic("len(dst) < len(src)")
}
b := block.BlockSize()
c := iv[:b]
m := iv[b:]
for o := 0; o < len(src); o += b {
t := src[o : o+b : o+b]
xor.Bytes(dst[o:o+b:o+b], src[o:o+b:o+b], m)
block.Decrypt(dst[o:o+b:o+b], dst[o:o+b:o+b])
xor.Bytes(dst[o:o+b:o+b], dst[o:o+b:o+b], c)
m = dst[o : o+b]
c = t
}
}