Golang AES/ECB/PKCS5 Encryption and decryption url-safe-base64

Source: Internet
Author: User
Tags key string pkcs5
This is a creation in Article, where the information may have evolved or changed.

Because the project needs to use a special encryption and decryption algorithm Golang AES/ECB/PKCS5, but the algorithm is not included in the standard library, after many unsuccessful attempts, finally decoding success, hereby share:

/*Description: Golang aes/ecb/pkcs5 encrypted decryption Date:2016-04-08author:herohenu*/Package Mainimport ("bytes" "Crypto/aes" "Crypto/cipher" "Encoding/base64" "FMT" "strings") Func main () {/**SRC the string to encrypt *key the key key length to encrypt can be any one of the 128bit, 192bit, 256bit * 16-bit key corresponding to 128bit*/src:= "0.56"Key:= "0123456789abcdef"crypted:=aesencrypt (SRC, key) aesdecrypt (crypted, []byte(Key)) Base64urldecode ("39w7dwtd_sbocm8ubng6qa")}func base64urldecode (Data String) ([]byte, error) {    varMissing = (4-len (data)%4)% 4Data+ = strings. Repeat ("=", missing) res, err:=Base64. Urlencoding.decodestring (data) fmt. Println ("Decodebase64urlsafe is:", String (res), err)returnBase64. Urlencoding.decodestring (data)}func Base64urlsafeencode (source []byte) String {//Base64 Url Safe is the same as Base64 but does not contain '/' and ' + ' (replaced by ' _ ' and '-') and trailing ' = ' is removed.Bytearr: =Base64. Stdencoding.encodetostring (source) Safeurl:= Strings. Replace (String (Bytearr), "/", "_", 1) Safeurl= Strings. Replace (Safeurl, "+", "-",-1) Safeurl= Strings. Replace (safeurl, "=", "",-1)    returnSafeurl}func Aesdecrypt (crypted, key []byte) []byte{block, err:=AES. Newcipher (Key)ifErr! =Nil {fmt. Println ("Err is:", Err)} Blockmode:=newecbdecrypter (Block) Origdata:= Make ([]byte, Len (crypted)) blockmode.cryptblocks (Origdata, crypted) Origdata=pkcs5unpadding (origdata) fmt. Println ("Source is:", Origdata, String (origdata))returnorigdata}func aesencrypt (src, key string) []byte{block, err:= AES. Newcipher ([]byte(key))ifErr! =Nil {fmt. Println ("Key Error1", Err)} ifsrc = = ""{fmt. Println ("Plain content Empty")} ECB:=newecbencrypter (block) content:= []byte(SRC) content=pkcs5padding (content, block. BlockSize ()) crypted:= Make ([]byte, Len (content)) ECB. Cryptblocks (crypted, content)//Common base64 encoded encryption differs from URLSAFE base64Fmt. PRINTLN ("Base64 Result:", base64. Stdencoding.encodetostring (crypted)) fmt. Println ("Base64urlsafe Result:", Base64urlsafeencode (crypted))returnCrypted}func pkcs5padding (ciphertext []byte, blockSizeint) []byte{padding:= Blocksize-len (ciphertext)%blockSize Padtext:= bytes. Repeat ([]byte{byte(padding)}, padding)returnAppend (ciphertext, padtext ...)} Func pkcs5unpadding (Origdata []byte) []byte{length:=Len (origdata)//remove the last byte unpadding timesUnpadding: =int(origdata[length-1])    returnOrigdata[:(Length-unpadding)]} Type ECB struct {b cipher. Block blockSizeint}func NEWECB (b cipher. Block)*ECB {return&ecb{b:b, Blocksize:b.blocksize (),}}type ecbencrypter ECB//Newecbencrypter Returns a blockmode which encrypts in electronic code book//mode, using the given Block.func Newecbencrypter (b cipher. Block) cipher. Blockmode {return(*ecbencrypter) (NEWECB (b))} Func (x*ecbencrypter) BlockSize ()int{returnx.blocksize}func (x*ecbencrypter) cryptblocks (DST, SRC []byte) {    ifLen (src)%x.blocksize! = 0{Panic ("Crypto/cipher:input not full blocks")    }    ifLen (DST) <Len (src) {Panic ("Crypto/cipher:output smaller than input")    }     forLen (src) > 0{x.b.encrypt (DST, src[:x.blocksize]) src=src[x.blocksize:] DST=dst[x.blocksize:]}} Type Ecbdecrypter ECB//Newecbdecrypter Returns a blockmode which decrypts in electronic code book//mode, using the given Block.func Newecbdecrypter (b cipher. Block) cipher. Blockmode {return(*ecbdecrypter) (NEWECB (b))} Func (x*ecbdecrypter) BlockSize ()int{returnx.blocksize}func (x*ecbdecrypter) cryptblocks (DST, SRC []byte) {    ifLen (src)%x.blocksize! = 0{Panic ("Crypto/cipher:input not full blocks")    }    ifLen (DST) <Len (src) {Panic ("Crypto/cipher:output smaller than input")    }     forLen (src) > 0{x.b.decrypt (DST, src[:x.blocksize]) src=src[x.blocksize:] DST=dst[x.blocksize:]}}

This is the author of a number of blogs and code, if you think this article is helpful to you, welcome to enjoy a cup of coffee as an encouragement to the author, thank you!

Acknowledgement:

aes:http://blog.studygolang.com/tag/aes_encrypt/of Go encryption and decryption

Yinheli:https://gist.github.com/yinheli/3370e0e901329b639be4

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.