forked from wumansgy/goEncrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tripledescbc.go
92 lines (82 loc) · 2 KB
/
tripledescbc.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
package goEncrypt
import (
"crypto/cipher"
"crypto/des"
"log"
"runtime"
)
/*
@Time : 2018/11/1 22:50
@Author : wuman
@File : TripleDES_CBC
@Software: GoLand
*/
/**
Triple des encryption and decryption
algorithm : Encryption: key one encryption -> key two decryption -> key three encryption
Decryption: key three decryption -> key two encryption -> key one decryption
*/
func TripleDesEncrypt(plainText ,key []byte,ivDes...byte)([]byte,error){
if len(key)!=24{
return nil,ErrKeyLengthTwentyFour
}
block, err := des.NewTripleDESCipher(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)
}
blockMode := cipher.NewCBCEncrypter(block, iv)
cipherText := make([]byte,len(paddingText))
blockMode.CryptBlocks(cipherText,paddingText)
return cipherText,nil
}
func TripleDesDecrypt(cipherText ,key []byte,ivDes...byte) ([]byte,error){
if len(key)!=24{
return nil,ErrKeyLengthTwentyFour
}
// 1. Specifies that the 3des decryption algorithm creates and returns a cipher.Block interface using the TDEA algorithm。
block, err := des.NewTripleDESCipher(key)
if err!=nil{
return nil,err
}
// 2. Delete the filling
// Before deleting, prevent the user from entering different keys twice and causing panic, so do an error handling
defer func(){
if err:=recover();err!=nil{
switch err.(type){
case runtime.Error:
log.Println("runtime error:",err,"Check that the key 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)
}
blockMode := cipher.NewCBCDecrypter(block, iv)
paddingText := make([]byte,len(cipherText)) //
blockMode.CryptBlocks(paddingText,cipherText)
plainText ,err:= PKCS5UnPadding(paddingText)
if err!=nil{
return nil,err
}
return plainText,nil
}