-
Notifications
You must be signed in to change notification settings - Fork 2
/
cipher.go
69 lines (59 loc) · 1.57 KB
/
cipher.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
// Package sm4 handle shangmi sm4 symmetric encryption algorithm
package sm4
import (
"crypto/cipher"
"fmt"
"github.com/hxx258456/ccgo/internal/subtle"
)
// BlockSize the sm4 block size in bytes.
const BlockSize = 16
const rounds = 32
// A cipher is an instance of SM4 encryption using a particular key.
type sm4Cipher struct {
enc []uint32
dec []uint32
}
// NewCipher creates and returns a new cipher.Block.
// The key argument should be the SM4 key,
func NewCipher(key []byte) (cipher.Block, error) {
k := len(key)
switch k {
default:
return nil, fmt.Errorf("sm4: invalid key size %d", k)
case 16:
break
}
return newCipher(key)
}
// newCipher creates and returns a new cipher.Block
// implemented in pure Go.
func newCipherGeneric(key []byte) (cipher.Block, error) {
c := sm4Cipher{make([]uint32, rounds), make([]uint32, rounds)}
expandKeyGo(key, c.enc, c.dec)
return &c, nil
}
func (c *sm4Cipher) BlockSize() int { return BlockSize }
func (c *sm4Cipher) Encrypt(dst, src []byte) {
if len(src) < BlockSize {
panic("sm4: input not full block")
}
if len(dst) < BlockSize {
panic("sm4: output not full block")
}
if subtle.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
panic("sm4: invalid buffer overlap")
}
encryptBlockGo(c.enc, dst, src)
}
func (c *sm4Cipher) Decrypt(dst, src []byte) {
if len(src) < BlockSize {
panic("sm4: input not full block")
}
if len(dst) < BlockSize {
panic("sm4: output not full block")
}
if subtle.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
panic("sm4: invalid buffer overlap")
}
decryptBlockGo(c.dec, dst, src)
}