Golang Aes 加密樣本

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

 Aes加密的一個樣本。供各位參考.

package mainimport (    "crypto/aes"    "crypto/cipher"    "fmt")func main() {    aesEnc := AesEncrypt{}    arrEncrypt, err := aesEnc.Encrypt("abcde")    if err != nil {        fmt.Println(arrEncrypt)        return    }    strMsg, err := aesEnc.Decrypt(arrEncrypt)    if err != nil {        fmt.Println(arrEncrypt)        return    }    fmt.Println(strMsg)}type AesEncrypt struct {}func (this *AesEncrypt) getKey() []byte {    strKey := "1234567890123456"    keyLen := len(strKey)    if keyLen < 16 {        panic("res key 長度不能小於16")    }    arrKey := []byte(strKey)    if keyLen >= 32 {        //取前32個位元組        return arrKey[:32]    }    if keyLen >= 24 {        //取前24個位元組        return arrKey[:24]    }    //取前16個位元組    return arrKey[:16]}//加密字串func (this *AesEncrypt) Encrypt(strMesg string) ([]byte, error) {    key := this.getKey()    var iv = []byte(key)[:aes.BlockSize]    encrypted := make([]byte, len(strMesg))    aesBlockEncrypter, err := aes.NewCipher(key)    if err != nil {        return nil, err    }    aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv)    aesEncrypter.XORKeyStream(encrypted, []byte(strMesg))    return encrypted, nil}//解密字串func (this *AesEncrypt) Decrypt(src []byte) (strDesc string, err error) {    defer func() {        //錯誤處理        if e := recover(); e != nil {            err = e.(error)        }    }()    key := this.getKey()    var iv = []byte(key)[:aes.BlockSize]    decrypted := make([]byte, len(src))    var aesBlockDecrypter cipher.Block    aesBlockDecrypter, err = aes.NewCipher([]byte(key))    if err != nil {        return "", err    }    aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv)    aesDecrypter.XORKeyStream(decrypted, src)    return string(decrypted), nil}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.