Skip to content

Commit 20f5ddc

Browse files
committed
修改了加密算法
1 parent d23d144 commit 20f5ddc

File tree

1 file changed

+45
-34
lines changed

1 file changed

+45
-34
lines changed

9.6.md

Lines changed: 45 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -54,40 +54,51 @@ Go语言的`crypto`里面支持对称加密的高级加解密包有:
5454

5555
package main
5656

57-
import (
58-
"crypto/aes"
59-
. "fmt"
60-
"os"
61-
)
62-
63-
func main() {
64-
msg := "My name is Astaxie"
65-
// some key, 16 Byte long
66-
key := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}
67-
68-
Println("len of message: ", len(msg))
69-
Println("len of key: ", len(key))
70-
// create the new cipher
71-
c, err := aes.NewCipher(key)
72-
if err != nil {
73-
Println("Error: NewCipher(%d bytes) = %s", len(key), err)
74-
os.Exit(-1)
75-
}
76-
77-
out := make([]byte, len(msg))
78-
79-
c.Encrypt(out, []byte(msg)) // encrypt the first half
80-
//c.Encrypt(msgbuf[16:32], out[16:32]) // encrypt the second half
81-
82-
Println("len of encrypted: ", len(out))
83-
Println(">> ", out)
84-
85-
// // now we decrypt our encrypted text
86-
plain := make([]byte, len(out))
87-
c.Decrypt(plain, out)
88-
89-
Println("msg: ", string(plain))
90-
}
57+
import (
58+
"crypto/aes"
59+
"crypto/cipher"
60+
"fmt"
61+
"os"
62+
)
63+
64+
var commonIV = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}
65+
66+
func main() {
67+
//需要去加密的字符串
68+
plaintext := []byte("My name is Astaxie")
69+
//如果传入加密串的话,plaint就是传入的字符串
70+
if len(os.Args) > 1 {
71+
plaintext = []byte(os.Args[1])
72+
}
73+
74+
//aes的加密字符串
75+
key_text := "astaxie12798akljzmknm.ahkjkljl;k"
76+
if len(os.Args) > 2 {
77+
key_text = os.Args[2]
78+
}
79+
80+
fmt.Println(len(key_text))
81+
82+
// 创建加密算法aes
83+
c, err := aes.NewCipher([]byte(key_text))
84+
if err != nil {
85+
fmt.Printf("Error: NewCipher(%d bytes) = %s", len(key_text), err)
86+
os.Exit(-1)
87+
}
88+
89+
//加密字符串
90+
cfb := cipher.NewCFBEncrypter(c, commonIV)
91+
ciphertext := make([]byte, len(plaintext))
92+
cfb.XORKeyStream(ciphertext, plaintext)
93+
fmt.Printf("%s=>%x\n", plaintext, ciphertext)
94+
95+
// 加密字符串
96+
cfbdec := cipher.NewCFBDecrypter(c, commonIV)
97+
plaintextCopy := make([]byte, len(plaintext))
98+
cfbdec.XORKeyStream(plaintextCopy, ciphertext)
99+
fmt.Printf("%x=>%s\n", ciphertext, plaintextCopy)
100+
}
101+
91102

92103
上面通过调用函数`aes.NewCipher`(参数key必须是16、24或者32位的[]byte,分别对应AES-128, AES-192或AES-256算法),返回了一个`cipher.Block`接口,这个接口实现了三个功能:
93104

0 commit comments

Comments
 (0)