-
Notifications
You must be signed in to change notification settings - Fork 0
/
3des.go
49 lines (45 loc) · 1.31 KB
/
3des.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
package pwd
import (
"crypto/cipher"
"crypto/des"
"fmt"
"strings"
"github.com/palp1tate/go-crypto-guard"
)
func GenThreeDES(password, threeDesKey string) (encryptedPassword string, err error) {
if len(threeDesKey) != 24 {
err = fmt.Errorf("the length of 3des key must be 24")
return
}
block, err := des.NewTripleDESCipher([]byte(threeDesKey))
if err != nil {
return
}
src := pwd.PKCS7Padding([]byte(password), block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, []byte(threeDesKey)[:block.BlockSize()])
blockMode.CryptBlocks(src, src)
encryptedPassword = fmt.Sprintf("%s$%s", pwd.ThreeDES, pwd.EncodeToString(src))
return
}
func VerifyThreeDES(password, encryptedPassword, threeDesKey string) (isValid bool, err error) {
parts := strings.Split(encryptedPassword, "$")
if len(parts) != 2 {
return false, fmt.Errorf("invalid encrypted password")
}
decodedPassword, err := pwd.DecodeString(parts[1])
if err != nil {
return
}
block, err := des.NewTripleDESCipher([]byte(threeDesKey))
if err != nil {
return
}
blockMode := cipher.NewCBCDecrypter(block, []byte(threeDesKey)[:block.BlockSize()])
blockMode.CryptBlocks(decodedPassword, decodedPassword)
encodedPassword, err := pwd.PKCS7UnPadding(decodedPassword)
if err != nil {
return
}
isValid = password == string(encodedPassword)
return
}