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
| package main
import ( "bytes" "crypto/aes" "crypto/cipher" "fmt" )
func main() { text := "abcfefghijklmnopqrst剩下的是我自己的加密内容" key := "qwertyuiopasdfgh"
iv := []byte("bbbbbbbbbbbbbbbb") iv2 := []byte("aaaaaaaaaaaaaaaa")
result := CBCEncrypt([]byte(text), []byte(key), iv) fmt.Println(string(CBCDecrypt(result, []byte(key), iv2))) }
func CBCEncrypt(text []byte, key []byte, iv []byte) []byte { b, err := aes.NewCipher(key) if err != nil { panic(err) } p := PKCS7Padding(text, b.BlockSize()) res := make([]byte, len(p)) cipher.NewCBCEncrypter(b, iv).CryptBlocks(res, p) return res }
func CBCDecrypt(t []byte, key []byte, iv []byte) []byte { b, err := aes.NewCipher(key) if err != nil { panic(err) } res := make([]byte, len(t)) cipher.NewCBCDecrypter(b, iv).CryptBlocks(res, t) return UnPKCS7Padding(res) }
func PKCS7Padding(t []byte, n int) []byte { l := n - len(t)%n var p []byte if l == 0 { p = bytes.Repeat([]byte{byte(n)}, n) } else { p = bytes.Repeat([]byte{byte(l)}, l) } return append(t, p...) }
func UnPKCS7Padding(t []byte) []byte { return t[:(len(t) - int(t[len(t)-1]))] }
|