-
Notifications
You must be signed in to change notification settings - Fork 1
/
block.go
48 lines (42 loc) · 1.16 KB
/
block.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
package ipcipher
import (
"crypto/aes"
"crypto/cipher"
"net"
)
// ipCipher is an instance of ipcipher encryption for a particular key.
type ipCipher struct {
key *Key
aes cipher.Block
}
// New creates and returns a new cipher.Block for IPcipher.
func New(key *Key) cipher.Block {
c, _ := aes.NewCipher(key[:])
return &ipCipher{key, c}
}
// BlockSize returns 0, because the block size is 32 and 128 at the same time.
func (i *ipCipher) BlockSize() int {
return 0
}
// Encrypt encrypts a net.IP compatible byte slice src into dst.
// Dst and src may point at the same memory.
func (i *ipCipher) Encrypt(dst, src []byte) {
if ip4 := net.IP(src).To4(); ip4 != nil {
EncryptIPv4(i.key, net.IP(dst).To4(), ip4)
} else if net.IP(src).To16() != nil {
i.aes.Encrypt(dst, src)
} else {
panic("Invalid IP address")
}
}
// Decrypt decrypts a net.IP compatible byte slice src into dst.
// Dst and src may point at the same memory.
func (i *ipCipher) Decrypt(dst, src []byte) {
if ip4 := net.IP(src).To4(); ip4 != nil {
DecryptIPv4(i.key, net.IP(dst).To4(), ip4)
} else if net.IP(src).To16() != nil {
i.aes.Decrypt(dst, src)
} else {
panic("Invalid IP address")
}
}