forked from wumansgy/goEncrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
descbc.go
93 lines (82 loc) · 1.77 KB
/
descbc.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package goEncrypt
import (
"crypto/cipher"
"crypto/des"
"log"
"runtime"
)
/*
@Time : 2018/11/1 21:28
@Author : wuman
@File : DES_CBC
@Software: GoLand
*/
/**
1. Group plaintext
DES CBC mode encryption and decryption, is an 8-byte block encryption
If the group is not an integer multiple of 8, you need to consider completing the 8 bits2.
*/
func init(){
log.SetFlags(log.Ldate|log.Lshortfile)
}
func DesCbcEncrypt(plainText ,key []byte,ivDes...byte)([]byte,error){
if len(key)!=8{
return nil,ErrKeyLengtheEight
}
block, err := des.NewCipher(key)
if err!=nil{
return nil,err
}
paddingText := PKCS5Padding(plainText, block.BlockSize())
var iv []byte
if len(ivDes)!=0{
if len(ivDes)!=8{
return nil,ErrIvDes
}else{
iv=ivDes
}
}else{
iv =[]byte(ivdes)
} // Initialization vector
blockMode := cipher.NewCBCEncrypter(block, iv)
cipherText := make([]byte,len(paddingText))
blockMode.CryptBlocks(cipherText,paddingText)
return cipherText,nil
}
func DesCbcDecrypt(cipherText ,key []byte,ivDes...byte) ([]byte,error){
if len(key)!=8{
return nil,ErrKeyLengtheEight
}
block, err := des.NewCipher(key)
if err!=nil{
return nil,err
}
defer func(){
if err:=recover();err!=nil{
switch err.(type){
case runtime.Error:
log.Println("runtime err:",err,"Check that the key or text is correct")
default:
log.Println("error:",err)
}
}
}()
var iv []byte
if len(ivDes)!=0{
if len(ivDes)!=8{
return nil,ErrIvDes
}else{
iv=ivDes
}
}else{
iv =[]byte(ivdes)
} // Initialization vector
blockMode := cipher.NewCBCDecrypter(block, iv)
plainText := make([]byte,len(cipherText))
blockMode.CryptBlocks(plainText,cipherText)
unPaddingText,err := PKCS5UnPadding(plainText)
if err!=nil{
return nil,err
}
return unPaddingText,nil
}