-
Notifications
You must be signed in to change notification settings - Fork 4
/
PBEWithMD5AndDES.go
73 lines (57 loc) · 1.8 KB
/
PBEWithMD5AndDES.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
package PBEWithMD5AndDES
import (
"fmt"
"strings"
"encoding/base64"
"crypto/cipher"
"crypto/des"
"crypto/md5"
)
func getDerivedKey(password string, salt []byte, count int) ([]byte, []byte) {
key := md5.Sum([]byte(password + string(salt)))
for i := 0; i < count - 1; i++ {
key = md5.Sum(key[:])
}
return key[:8], key[8:]
}
func Encrypt(password string, obtenationIterations int, plainText string, salt []byte) (string, error) {
padNum := byte(8 - len(plainText) % 8)
for i := byte(0); i < padNum; i++ {
plainText += string(padNum)
}
dk, iv := getDerivedKey(password, salt, obtenationIterations)
block,err := des.NewCipher(dk)
if err != nil {
return "", err
}
encrypter := cipher.NewCBCEncrypter(block, iv)
encrypted := make([]byte, len(plainText))
encrypter.CryptBlocks(encrypted, []byte(plainText))
return base64.StdEncoding.EncodeToString(encrypted), nil
}
func Decrypt(password string, obtenationIterations int, cipherText string, salt []byte) (string, error) {
msgBytes, err := base64.StdEncoding.DecodeString(cipherText)
if err != nil {
return "", err
}
dk, iv := getDerivedKey(password, salt, obtenationIterations)
block,err := des.NewCipher(dk)
if err != nil {
return "", err
}
decrypter := cipher.NewCBCDecrypter(block, iv)
decrypted := make([]byte, len(msgBytes))
decrypter.CryptBlocks(decrypted, msgBytes)
decryptedString := strings.TrimRight(string(decrypted), "\x01\x02\x03\x04\x05\x06\x07\x08")
return decryptedString, nil
}
func main() {
salt := []byte{0xFF, 0x2B, 0x38, 0x30, 0xF8, 0x61, 0xEF, 0x99}
password := "my_secret_password"
iterations := 222
originalText := "mythings"
res, err := Encrypt(password, iterations, originalText, salt)
fmt.Println("encripted", res, err)
res, err = Decrypt(password, iterations, res, salt)
fmt.Println("decripted", res, err)
}