修改了加密算法
This commit is contained in:
65
9.6.md
65
9.6.md
@@ -54,40 +54,51 @@ Go语言的`crypto`里面支持对称加密的高级加解密包有:
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
. "fmt"
|
||||
"os"
|
||||
)
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
msg := "My name is Astaxie"
|
||||
// some key, 16 Byte long
|
||||
key := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}
|
||||
var commonIV = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}
|
||||
|
||||
Println("len of message: ", len(msg))
|
||||
Println("len of key: ", len(key))
|
||||
// create the new cipher
|
||||
c, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
Println("Error: NewCipher(%d bytes) = %s", len(key), err)
|
||||
os.Exit(-1)
|
||||
}
|
||||
func main() {
|
||||
//需要去加密的字符串
|
||||
plaintext := []byte("My name is Astaxie")
|
||||
//如果传入加密串的话,plaint就是传入的字符串
|
||||
if len(os.Args) > 1 {
|
||||
plaintext = []byte(os.Args[1])
|
||||
}
|
||||
|
||||
out := make([]byte, len(msg))
|
||||
//aes的加密字符串
|
||||
key_text := "astaxie12798akljzmknm.ahkjkljl;k"
|
||||
if len(os.Args) > 2 {
|
||||
key_text = os.Args[2]
|
||||
}
|
||||
|
||||
c.Encrypt(out, []byte(msg)) // encrypt the first half
|
||||
//c.Encrypt(msgbuf[16:32], out[16:32]) // encrypt the second half
|
||||
fmt.Println(len(key_text))
|
||||
|
||||
Println("len of encrypted: ", len(out))
|
||||
Println(">> ", out)
|
||||
// 创建加密算法aes
|
||||
c, err := aes.NewCipher([]byte(key_text))
|
||||
if err != nil {
|
||||
fmt.Printf("Error: NewCipher(%d bytes) = %s", len(key_text), err)
|
||||
os.Exit(-1)
|
||||
}
|
||||
|
||||
// // now we decrypt our encrypted text
|
||||
plain := make([]byte, len(out))
|
||||
c.Decrypt(plain, out)
|
||||
//加密字符串
|
||||
cfb := cipher.NewCFBEncrypter(c, commonIV)
|
||||
ciphertext := make([]byte, len(plaintext))
|
||||
cfb.XORKeyStream(ciphertext, plaintext)
|
||||
fmt.Printf("%s=>%x\n", plaintext, ciphertext)
|
||||
|
||||
// 加密字符串
|
||||
cfbdec := cipher.NewCFBDecrypter(c, commonIV)
|
||||
plaintextCopy := make([]byte, len(plaintext))
|
||||
cfbdec.XORKeyStream(plaintextCopy, ciphertext)
|
||||
fmt.Printf("%x=>%s\n", ciphertext, plaintextCopy)
|
||||
}
|
||||
|
||||
Println("msg: ", string(plain))
|
||||
}
|
||||
|
||||
上面通过调用函数`aes.NewCipher`(参数key必须是16、24或者32位的[]byte,分别对应AES-128, AES-192或AES-256算法),返回了一个`cipher.Block`接口,这个接口实现了三个功能:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user