From 5dbb0ab8c5e9401fd274be2b76e18ae3f27ed280 Mon Sep 17 00:00:00 2001 From: astaxie Date: Tue, 30 Oct 2012 14:09:27 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E5=8A=A0=E5=AF=86?= =?UTF-8?q?=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 9.6.md | 65 ++++++++++++++++++++++++++++++++++------------------------ 1 file changed, 38 insertions(+), 27 deletions(-) diff --git a/9.6.md b/9.6.md index 504b2d7d..124c626c 100644 --- a/9.6.md +++ b/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`接口,这个接口实现了三个功能: