In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains the "what Go encryption and decryption algorithms", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "which Go encryption and decryption algorithms" bar!
Md5
MD5 information digest algorithm is a widely used cryptographic hash function, which can produce a 128bit (hexadecimal, 32-character) hash value (hash value) to ensure complete and consistent information transmission.
Func GetMd5String (s string) string {h: = md5.New () h.Write ([] byte (s)) return hex.EncodeToString (h.Sum (nil))}
Hmac
HMAC is an acronym for key-related hash message authentication code (Hash-based Message Authentication Code)
It uses a standard algorithm to mix key into the calculation process in the process of calculating hash.
Unlike our custom plus salt algorithm, the Hmac algorithm is common to all hash algorithms, whether MD5 or SHA-1. Using Hmac instead of our own salt algorithm can make the program algorithm more standardized and more secure.
Example
/ / key arbitrarily set data to encrypt data func Hmac (key, data string) string {hash:= hmac.New (md5.New, [] byte (key)) / / create the corresponding md5 hash encryption algorithm hash.Write ([] byte (data)) return hex.EncodeToString (hash.Sum ([] byte ("))} func HmacSha256 (key, data string) string {hash:= hmac.New (sha256.New) [] byte (key)) / / create the corresponding sha256 hash encryption algorithm hash.Write ([] byte (data)) return hex.EncodeToString (hash.Sum ([] byte (")}
Sha1
SHA-1 can generate a 160-bit (20-byte) hash value called a message digest, which is usually rendered in the form of 40 hexadecimal numbers.
Func Sha1 (data string) string {sha1: = sha1.New () sha1.Write ([] byte (data)) return hex.EncodeToString (sha1.Sum ([] byte (")}
AES
The Advanced encryption Standard (Advanced Encryption Standard,AES) in cryptography, also known as Rijndael encryption, is a block encryption standard adopted by the federal government of the United States. This standard, which is used to replace the original DES (Data Encryption Standard), has been analyzed by many parties and is widely used all over the world. There are three common solutions in AES, which are AES-128, AES-192, and AES-256. If you use real 128-bit encryption or even 256-bit encryption, it takes a long time for brute force attacks to succeed.
AES has five encryption modes:
Codebook mode (Electronic Codebook Book (ECB)),
Password block link mode (Cipher Block Chaining (CBC)),
Calculator mode (Counter (CTR)),
Password feedback mode (Cipher FeedBack (CFB))
Output feedback mode (Output FeedBack (OFB))
ECB mode
For security reasons, golang does not support ECB mode by default.
Package main import ("crypto/aes"fmt") func AESEncrypt (src [] byte, key [] byte) (encrypted [] byte) {cipher, _: = aes.NewCipher (generateKey (key)) length: = (len (src) + aes.BlockSize) / aes.BlockSize plain: = make ([] byte, length*aes.BlockSize) copy (plain) Src) pad: = byte (len (plain)-len (src)) for I: = len (src) I < len (plain); iTunes + {plain [I] = pad} encrypted = make ([] byte, len (plain)) / / Block encryption for bs, be: = 0, cipher.BlockSize () Bs 0 {trim = len (decrypted)-int (decrypted [len (decrypted)-1])} return decrypted [: trim]} func generateKey (key [] byte) (genKey [] byte) {genKey = make ([] byte, 16) copy (genKey, key) for I: = 16; I < len (key); {for j: = 0; j < 16 & & I < len (key) J, I = juni1, iTun1 {genKey [j] ^ = key [I]} return genKey} func main () {source:= "hello world" fmt.Println ("original character:", source) / / 16byte key key:= "1443flfsaWfdas" encryptCode:=AESEncrypt ([] byte (source), [] byte (key)) fmt.Println ("ciphertext:" String (encryptCode)) decryptCode:=AESDecrypt (encryptCode, [] byte (key)) fmt.Println ("decryption:", string (decryptCode))}
CBC mode
Package main import ("bytes"crypto/aes"fmt"crypto/cipher"encoding/base64") func main () {orig: = "hello world" key: = "0123456789012345" fmt.Println ("original:", orig) encryptCode: = AesEncrypt (orig, key) fmt.Println ("ciphertext:", encryptCode) decryptCode: = AesDecrypt (encryptCode Key) fmt.Println ("decryption result:", decryptCode)} func AesEncrypt (orig string, key string) string {/ / convert to byte array origData: = [] byte (orig) k: = [] byte (key) / / packet key / / NewCipher this function limits the length of input k to 16, 24 or 32 block _: = aes.NewCipher (k) / / get the length of the key block blockSize: = block.BlockSize () / / completion code origData = PKCS7Padding (origData, blockSize) / / encryption mode blockMode: = cipher.NewCBCEncrypter (block, k [: blockSize]) / / create array cryted: = make ([] byte, len (origData)) / / encryption blockMode.CryptBlocks (cryted) OrigData) return base64.StdEncoding.EncodeToString (cryted)} func AesDecrypt (cryted string, key string) string {/ / into a byte array crytedByte, _: = base64.StdEncoding.DecodeString (cryted) k: = [] byte (key) / / packet key block _: = aes.NewCipher (k) / / get the length of the key block blockSize: = block.BlockSize () / / encryption mode blockMode: = cipher.NewCBCDecrypter (block, k [: blockSize]) / / create an array orig: = make ([] byte, len (crytedByte)) / / decrypt blockMode.CryptBlocks (orig) CrytedByte) / / de-completion code orig = PKCS7UnPadding (orig) return string (orig)} / / complement / / AES encrypted data block packet length must be 128bit (byte [16]) The key length can be any one of 128bit (byte [16]), 192bit (byte [24]), or 256bit (byte [32]). Func PKCS7Padding (ciphertext [] byte, blocksize int) [] byte {padding: = blocksize-len (ciphertext)% blocksize padtext: = bytes.Repeat ([] byte {byte (padding)}, padding) return append (ciphertext, padtext...)} / / Decode func PKCS7UnPadding (origData [] byte) [] byte {length: = len (origData) unpadding: = int (origDatalength [- 1]) return origData [: (length- unpadding)]}
CRT mode
Package main import ("bytes"crypto/aes"crypto/cipher"fmt") / / encryption func aesCtrCrypt (plainText [] byte, key [] byte) ([] byte, error) {/ / 1. Create the cipher.Block interface block, err: = aes.NewCipher (key) if err! = nil {return nil, err} / / 2. Create a grouping mode in the crypto/cipher package iv: = bytes.Repeat ([] byte ("1"), block.BlockSize () stream: = cipher.NewCTR (block, iv) / / 3. Encryption dst: = make ([] byte, len (plainText)) stream.XORKeyStream (dst, plainText) return dst, nil} func main () {source:= "hello world" fmt.Println ("original character:", source) key:= "1443flfsaWfdasds" encryptCode,_:=aesCtrCrypt ([] byte (source), [] byte (key)) fmt.Println ("ciphertext:", string (encryptCode)) decryptCode _: = aesCtrCrypt (encryptCode, [] byte (key)) fmt.Println ("decryption:", string (decryptCode))} CFB mode package main import ("crypto/aes"crypto/cipher"crypto/rand"encoding/hex"fmt"io") func AesEncryptCFB (origData [] byte, key [] byte) (encrypted [] byte) {block Err: = aes.NewCipher (key) if err! = nil {/ / panic (err)} encrypted = make ([] byte, aes.BlockSize+len (origData)) iv: = encrypted [: aes.BlockSize] if _, err: = io.ReadFull (rand.Reader, iv) Err! = nil {/ / panic (err)} stream: = cipher.NewCFBEncrypter (block, iv) stream.XORKeyStream (encrypted [aes.BlockSize:], origData) return encrypted} func AesDecryptCFB (encrypted [] byte, key [] byte) (decrypted [] byte) {block _: = aes.NewCipher (key) if len (encrypted) < aes.BlockSize {panic ("ciphertext too short")} iv: = encrypted [: aes.BlockSize] encryptedencrypted = encrypted [aes.BlockSize:] stream: = cipher.NewCFBDecrypter (block, iv) stream.XORKeyStream (encrypted, encrypted) return encrypted} func main () {source:= "hello world" fmt.Println ("original character:" Source) key:= "ABCDEFGHIJKLMNO1" / / 16-bit encryptCode:=AesEncryptCFB ([] byte (source), [] byte (key)) fmt.Println ("ciphertext:", hex.EncodeToString (encryptCode)) decryptCode:=AesDecryptCFB (encryptCode, [] byte (key)) fmt.Println ("decryption:", string (decryptCode))}
OFB mode
Package main import ("bytes"crypto/aes"crypto/cipher"crypto/rand"encoding/hex"fmt"io") func aesEncryptOFB (data [] byte,key [] byte) ([] byte, error) {data = PKCS7Padding (data, aes.BlockSize) block, _: = aes.NewCipher ([] byte (key)) out: = make ([] byte) Aes.BlockSize + len (data)) iv: = out [: aes.BlockSize] if _, err: = io.ReadFull (rand.Reader, iv) Err! = nil {return nil, err} stream: = cipher.NewOFB (block, iv) stream.XORKeyStream (out [aes.BlockSize:], data) return out, nil} func aesDecryptOFB (data [] byte,key [] byte) ([] byte, error) {block _: = aes.NewCipher ([] byte (key)) iv: = data [: aes.BlockSize] datadata = data [aes.BlockSize:] if len (data)% aes.BlockSize! = 0 {return nil, fmt.Errorf ("data is not a multiple of the block size")} out: = make ([] byte, len (data) mode: = cipher.NewOFB (block, iv) mode.XORKeyStream (out Data) out= PKCS7UnPadding (out) return out, nil} / complement / / AES encrypted block packet length must be 128bit (byte [16]) The key length can be any one of 128bit (byte [16]), 192bit (byte [24]), or 256bit (byte [32]). Func PKCS7Padding (ciphertext [] byte, blocksize int) [] byte {padding: = blocksize-len (ciphertext)% blocksize padtext: = bytes.Repeat ([] byte {byte (padding)}, padding) return append (ciphertext) Padtext...)} / / Decode func PKCS7UnPadding (origData [] byte) [] byte {length: = len (origData) unpadding: = int (origdata [length-1]) return origData [: (length- unpadding)]} func main () {source:= "hello world" fmt.Println ("original character:", source) key:= "111111111111111111" / / 16-bit 32-bit encryptCode _: = aesEncryptOFB ([] byte (source), [] byte (key)) fmt.Println ("ciphertext:", hex.EncodeToString (encryptCode)) decryptCode,_:=aesDecryptOFB (encryptCode, [] byte (key)) fmt.Println ("decryption:", string (decryptCode))}
RSA encryption
First use openssl to generate public and private keys
Package main import ("crypto/rand"crypto/rsa"crypto/x509"encoding/base64"encoding/pem"errors"fmt") / / Private key generation / / openssl genrsa-out rsa_private_key.pem 1024 var privateKey = [] byte (`- BEGIN RSA PRIVATE KEY- MIICWwIBAAKBgQDcGsUIIAINHfRTdMmgGwLrjzfMNSrtgIf4EGsNaYwmC1GjF/bM h0Mcm10oLhNrKNYCTTQVGGIxuc5heKd1gOzb7bdTnCDPPZ7oV7p1B9Pud+6zPaco qDz2M24vHFWYY2FbIIJh8fHhKcfXNXOLovdVBE7Zy682X1+R1lRK8D+vmQIDAQAB AoGAeWAZvz1HZExca5k/hpbeqV+0+VtobMgwMs96+U53BpO/VRzl8Cu3CpNyb7HY 64L9YQ+J5QgpPhqkgIO0dMu/0RIXsmhvr2gcxmKObcqT3JQ6S4rjHTln49I2sYTz 7JEH4TcplKjSjHyq5MhHfA+CV2/) AB2BO6G8limu7SheXuvECQQDwOpZrZDeTOOBk z1vercawd+J9ll/FZYttnrWYTI1sSF1sNfZ7dUXPyYPQFZ0LQ1bhZGmWBZ6a6wd9 R+PKlmJvAkEA6o32c/WEXxW2zeh28sOO4wqUiBYq3L3hFObhcsUAY8jfykQefW8q yPuuL02jLIajFWd0itjvIrzWnVmoUuXydwJAXGLrvllIVkIlah+lATprkypH3Gyc YFnxCTNkOzIVoXMjGp6WMFylgIfLPZdSUiaPnxby1FNM7987fh7Lp/m12QJAK9iL 2JNtwkSR3p305oOuAz0oFORn8MnB+KFMRaMT9pNHWk0vke0lB1sc7ZTKyvkEJW0o eQgic9DvIYzwDUcU8wJAIkKROzuzLi9AvLnLUrSdI6998lmeYO9x7pwZPukz3era zncjRK3pbVkv0KrKfczuJiRlZ7dUzVO0b6QJr8TRAA==-END RSA PRIVATE KEY- `) / / Public key: generate / / openssl rsa-in rsa_private_key.pem-pubout-out rsa_public_key.pem var publicKey = [] byte (`-BEGIN PUBLIC KEY- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcGsUIIAINHfRTdMmgGwLrjzfM NSrtgIf4EGsNaYwmC1GjF/bMh0Mcm10oLhNrKNYCTTQVGGIxuc5heKd1gOzb7bdT nCDPPZ7oV7p1B9Pud+6zPacoqDz2M24vHFWYY2FbIIJh8fHhKcfXNXOLovdVBE7Z y682X1+R1lRK8D+vmQIDAQAB-END PUBLIC KEY- `) / / based on the private key Encrypt func RsaEncrypt (origData [] byte) ([] byte) Error) {/ / decrypt the public key block in pem format, _: = pem.Decode (publicKey) if block = = nil {return nil, errors.New ("public key error")} / / parse the public key pubInterface, err: = x509.ParsePKIXPublicKey (block.Bytes) if err! = nil {return nil Err} / / Type assertion pub: = pubInterface. (* rsa.PublicKey) / / encryption return rsa.EncryptPKCS1v15 (rand.Reader, pub, origData)} / / decrypt func RsaDecrypt (ciphertext [] byte) ([] byte, error) {/ / decrypt block, _: = pem.Decode (privateKey) if block = = nil {return nil Errors.New ("private key error!")} / / parse the private key priv in PKCS1 format, err: = x509.ParsePKCS1PrivateKey (block.Bytes) if err! = nil {return nil, err} / / decrypt return rsa.DecryptPKCS1v15 (rand.Reader, priv, ciphertext)} func main () {data _: = RsaEncrypt ([] byte ("hello world")) fmt.Println (base64.StdEncoding.EncodeToString (data)) origData, _: = RsaDecrypt (data) fmt.Println (string (origData))} Thank you for reading The above is the content of "what are the Go encryption and decryption algorithms". After the study of this article, I believe you have a deeper understanding of what Go encryption and decryption algorithms there are, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.