SoFunction
Updated on 2025-03-05

Summary of common encryption algorithms in Golang

If you want to use my library below

You can go directly to get my github

go get -u /hybpjx/InverseAlgorithm

1.md5 encryption-irreversible

The MD5 information digest algorithm is a widely used password hash function that can produce a hash value of 128 bits (hexadecimal, 32 characters) to ensure that the information transmission is complete and consistent.

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
)

The first type

// MD5Str md5 verificationfunc MD5Str(src string) string {
    h := ()
    ([]byte(src)) // The string that needs to be encrypted is    ("%s\n", ((nil))) // Output encryption results    return ((nil))
}

The second type

// MD5Str2 md5 verificationfunc MD5Str2(src string) string {
    return ("%x", ([]byte(src)))
}

Encryption - irreversible

HMAC is the abbreviation of Hash-based Message Authentication Code for key-related hashing. It uses a standard algorithm to mix keys into the calculation process during the hashing process.

Unlike our customized salt algorithm, the Hmac algorithm is common for all hashing algorithms, whether it is MD5 or SHA-1. Using Hmac instead of our own salt algorithm can make the program algorithm more standardized and safer.

hmac-md5 encryption

//Set the key at will. Data to encrypt the data. 
func Hmac(key, data string) string {
    // Create the corresponding md5 hash encryption algorithm    hash:= (, []byte(key)) 
 
    ([]byte(data))
 
    return (([]byte("")))
 
}

hamacsha1 encryption

// HmacSha1 hmacSha1 encryption key set at will data to encrypt datafunc HmacSha1(src, key string) string {
    m := (, []byte(key))
    ([]byte(src))
    return ((nil))
}

hamacsha 256 Encryption

// HmacSHA256 hmacSha256 verification key set at will data to encrypt datafunc HmacSHA256(key, src string) string {
    m := (, []byte(key))
    ([]byte(src))
    return ((nil))
}

hmacsha512 encryption

// HmacSHA512 hmacSha512 Verificationfunc HmacSHA512(key, src string) string {
    m := (, []byte(key))
    ([]byte(src))
    return ((nil))
}

hamasha call

package main
 
import (
    "crypto/hmac"
    "crypto/md5"
    "crypto/sha1"
    "crypto/sha256"
    "crypto/sha512"
    "encoding/hex"
    "fmt"
)
 
// Hmac hmac verification key set at will data to encrypt datafunc Hmac(key, data string) string {
 
    hash := (, []byte(key)) // Create the corresponding md5 hash encryption algorithm 
    ([]byte(data))
 
    return (([]byte("")))
 
}
 
// HmacSHA256 hmacSha256 encryption key set at will data to encrypt datafunc HmacSHA256(key, src string) string {
    m := (, []byte(key))
    ([]byte(src))
    return ((nil))
}
 
// HmacSHA512 hmacSha512 encryption key set at will data to encrypt datafunc HmacSHA512(key, src string) string {
    m := (, []byte(key))
    ([]byte(src))
    return ((nil))
}
 
// HmacSha1 hmacSha1 encryption key set at will data to encrypt datafunc HmacSha1(src, key string) string {
    m := (, []byte(key))
    ([]byte(src))
    return ((nil))
}
 
// SHA256Str sha256 encryptionfunc SHA256Str(src string) string {
    h := ()
    ([]byte(src)) // The string that needs to be encrypted is    // ("%s\n", ((nil))) // Output encryption result    return ((nil))
}
 
func main() {
    hmac_ := Hmac("hybpjx", "Beginning")
    hamcsha1 := HmacSha1("hybpjx", "Beginning")
    hamcsha256 := HmacSHA256("hybpjx", "Beginning")
    hamacsha512 := HmacSHA512("hybpjx", "Beginning")
    (hmac_)
    (hamcsha1)
    (hamcsha256)
    (hamacsha512)
}

result

d8801f70df7891764116e1ac003f7189
60d68e01c8a86f3b87e4e147e9f0fadce2a69661
b3f8ddf991288036864761a55046877adfe4f78ec9a89bb63932af92689b139f
b9b1fca0fe91522482ee1b2161e57d67482af6ef371614365b918c31ce774f9126ed627e378a063145f404ff2de7bd84f8e4798c385662ef4749e58e9209ca63

Encryption - irreversible

sha1

SHA-1 can generate a 160-bit (20-byte) hash value called a message digest, which is usually presented in 40 hexadecimal numbers.

func Sha1(data string) string {
    sha1_ := ()
    sha1_.Write([]byte(data))
    return (sha1_.Sum([]byte("")))
}

sha256

The hash length used by the SHA256 algorithm is 256 bits. This is an abstract class. The only implementation of this class is SHA256Managed.

// SHA256 sha256 encryptionfunc SHA256(src string) string {
    h := ()
    // The string that needs to be encrypted is    ([]byte(src))
    // ("%s\n", ((nil))) // Output encryption result    return ((nil))
}

sha512

SHA (Secure Hash Algorithm, translated as Secure Hash Algorithm) is a series of cryptographic hash functions designed by the National Security Agency (NSA) and published by the National Institute of Standards and Technology (NIST).

// SHA512 sha512 encryptionfunc SHA512(src string) string {
    h := ()
    // The string that needs to be encrypted is    ([]byte(src))
    // ("%s\n", ((nil))) // Output encryption result    return ((nil))
}

Sha call

package main
 
import (
    "crypto/sha1"
    "crypto/sha256"
    "crypto/sha512"
    "encoding/hex"
    "fmt"
)
 
func Sha1(data string) string {
    sha1_ := ()
    sha1_.Write([]byte(data))
    return (sha1_.Sum([]byte("")))
}
 
// SHA256 sha256 encryptionfunc SHA256(src string) string {
    h := ()
    // The string that needs to be encrypted is    ([]byte(src))
    // ("%s\n", ((nil))) // Output encryption result    return ((nil))
}
 
// SHA512 sha512 encryptionfunc SHA512(src string) string {
    h := ()
    // The string that needs to be encrypted is    ([]byte(src))
    // ("%s\n", ((nil))) // Output encryption result    return ((nil))
}
 
func main() {
    _sha1 := Sha1("Beginning")
    _sha256 := SHA256("Beginning")
    _sha512 := SHA512("Beginning")
    (_sha1)
    (_sha256)
    (_sha512)
}

result

7bac01cc58a26f3cb280b0466794a89441279946
6ef99e6d3fe34a46afcdc438435728fe95ffdab18e389ddd31609edd6729b11d
0c04e9b79f488646d0eac6f65468248507939d643cc92709b14eb0d18d8f13db509ed5ccd3312d6c234408185a4611a42525dce9e8d32255640f56a2f836635a

Encryption Decryption

encryption

// BASE64StdEncode base encodingfunc BASE64StdEncode(src string) string {
    return ([]byte(src))
}

Decryption

// BASE64StdDecode base decodingfunc BASE64StdDecode(src string) string {
    a, err := (src)
    if err != nil {
        _ = ("Decryption failed, %v\n", err)
    }
    return string(a)
}

base64 call

package main
 
import (
    "encoding/base64"
    "fmt"
)
 
// BASE64StdEncode base encodingfunc BASE64StdEncode(src string) string {
    return ([]byte(src))
}
 
// BASE64StdDecode base decodingfunc BASE64StdDecode(src string) string {
    a, err := (src)
    if err != nil {
        _ = ("Decryption failed, %v\n", err)
    }
    return string(a)
}
 
func main() {
    encodeBase64 := BASE64StdEncode("hybpjx")
    decodeBase64 := BASE64StdDecode(encodeBase64)
    (encodeBase64)
    (decodeBase64)
}

result

aHlicGp4
hybpjx

encryption

Advanced Encryption Standard (AES), also known as Rijndael encryption in cryptography. This standard is used to replace the original DES, and has been analyzed by multiple parties and is widely used worldwide. After five years of selection process, it was published on FIPS PUB 197 on November 26, 2001 and became a valid standard on May 26, 2002. In 2006, advanced encryption standards have become one of the most popular algorithms in symmetric key encryption.

Since the encryption and decryption keys are the same, AES is symmetric encryption

package main
 
import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "fmt"
)
 
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := ([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}
 
func PKCS7UnPadding(origData []byte) []byte {
    length := len(origData)
    unpadding := int(origData[length-1])
    return origData[:(length - unpadding)]
}
 
//AES encryptionfunc AesEncrypt(origData, key []byte) ([]byte, error) {
    block, err := (key)
    if err != nil {
        return nil, err
    }
    blockSize := ()
    origData = PKCS7Padding(origData, blockSize)
    blockMode := (block, key[:blockSize])
    crypted := make([]byte, len(origData))
    (crypted, origData)
    return crypted, nil
}
 
//AES decryptionfunc AesDecrypt(crypted, key []byte) ([]byte, error) {
    block, err := (key)
    if err != nil {
        return nil, err
    }
    blockSize := ()
    blockMode := (block, key[:blockSize])
    origData := make([]byte, len(crypted))
    (origData, crypted)
    origData = PKCS7UnPadding(origData)
    return origData, nil
}
 
func main() {
    text := "Fight the tiger tonight"
    AesKey := []byte("0f90023fc9ae101e") //The key length is a multiple of 16    ("Plain text: %s\nKey: %s\n", text, string(AesKey))
    encrypted, err := AesEncrypt([]byte(text), AesKey)
    if err != nil {
        panic(err)
    }
    ("After encryption: %s\n", (encrypted))
    origin, err := AesDecrypt(encrypted, AesKey)
    if err != nil {
        panic(err)
    }
    ("Decrypted plain text: %s\n", string(origin))
}

CBC method

package main
 
import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "encoding/hex"
    "log"
)
 
func AesEncryptCBC(origData []byte, key []byte) (encrypted []byte) {
    // Grouping key    // NewCipher This function limits the length of input k must be 16, 24 or 32    block, _ := (key)
    blockSize := ()                              // Get the length of the key block    origData = pkcs5Padding(origData, blockSize)                // Complete code    blockMode := (block, key[:blockSize]) // Encryption mode    encrypted = make([]byte, len(origData))                     // Create an array    (encrypted, origData)                  // Encryption    return encrypted
}
func AesDecryptCBC(encrypted []byte, key []byte) (decrypted []byte) {
    block, _ := (key)                              // Grouping key    blockSize := ()                              // Get the length of the key block    blockMode := (block, key[:blockSize]) // Encryption mode    decrypted = make([]byte, len(encrypted))                    // Create an array    (decrypted, encrypted)                 // Decrypt    decrypted = pkcs5UnPadding(decrypted)                       // Remove the complete code    return decrypted
}
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := ([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}
func pkcs5UnPadding(origData []byte) []byte {
    length := len(origData)
    unpadding := int(origData[length-1])
    return origData[:(length - unpadding)]
}
func main() {
    origData := []byte("460154561234") // Data to be encrypted    key := []byte("9876787656785679")  // Encrypted key    ("original:", string(origData))
 
    ("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------)
    encrypted := AesEncryptCBC(origData, key)
    ("Secret text(hex):", (encrypted))
    ("Secret text(base64):", (encrypted))
    decrypted := AesDecryptCBC(encrypted, key)
    ("Decryption result:", string(decrypted))
}

ECB method

package main
 
import (
    "crypto/aes"
    "encoding/base64"
    "encoding/hex"
    "log"
)
 
 
func AesEncryptECB(origData []byte, key []byte) (encrypted []byte) {
    cipher, _ := (generateKey(key))
    length := (len(origData) + ) / 
    plain := make([]byte, length*)
    copy(plain, origData)
    pad := byte(len(plain) - len(origData))
    for i := len(origData); i < len(plain); i++ {
        plain[i] = pad
    }
    encrypted = make([]byte, len(plain))
    // Packet block encryption    for bs, be := 0, (); bs <= len(origData); bs, be = bs+(), be+() {
        (encrypted[bs:be], plain[bs:be])
    }
 
    return encrypted
}
func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte) {
    cipher, _ := (generateKey(key))
    decrypted = make([]byte, len(encrypted))
    //
    for bs, be := 0, (); bs < len(encrypted); bs, be = bs+(), be+() {
        (decrypted[bs:be], encrypted[bs:be])
    }
 
    trim := 0
    if len(decrypted) > 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 = j+1, i+1 {
            genKey[j] ^= key[i]
        }
    }
    return genKey
}
 
func main() {
    origData := []byte("460154561234") // Data to be encrypted    key := []byte("9876787656785679")  // Encrypted key    ("original:", string(origData))
 
    ("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------)
    encrypted := AesEncryptECB(origData, key)
    ("Secret text(hex):", (encrypted))
    ("Secret text(base64):", (encrypted))
    decrypted := AesDecryptECB(encrypted, key)
    ("Decryption result:", string(decrypted))
}

CFB Method

package main
 
import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/base64"
    "encoding/hex"
    "io"
    "log"
)
 
func AesEncryptCFB(origData []byte, key []byte) (encrypted []byte) {
    block, err := (key)
    if err != nil {
        panic(err)
    }
    encrypted = make([]byte, +len(origData))
    iv := encrypted[:]
    if _, err := (, iv); err != nil {
        panic(err)
    }
    stream := (block, iv)
    (encrypted[:], origData)
    return encrypted
}
func AesDecryptCFB(encrypted []byte, key []byte) (decrypted []byte) {
    block, _ := (key)
    if len(encrypted) <  {
        panic("ciphertext too short")
    }
    iv := encrypted[:]
    encrypted = encrypted[:]
 
    stream := (block, iv)
    (encrypted, encrypted)
    return encrypted
}
func main() {
    origData := []byte("460154561234") // Data to be encrypted    key := []byte("9876787656785679")  // Encrypted key    ("original:", string(origData))
 
    ("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------)
    encrypted := AesEncryptCFB(origData, key)
    ("Secret text(hex):", (encrypted))
    ("Secret text(base64):", (encrypted))
    decrypted := AesDecryptCFB(encrypted, key)
    ("Decryption result:", string(decrypted))
}

encryption

RSA is an excellent encryption algorithm based on the public key cryptography system. It was proposed by Rivest, Shamir and Adleman of the United States in 1978.

The RSA algorithm is a packet cryptographic system algorithm, and its confidentiality is based on the difficulty of factoring decomposition of combined numbers with large prime factors (based on the difficulty of large number decomposition). The public key and the private key are functions of a pair of large prime numbers. The difficulty of recovering a plaintext from a public key and a ciphertext is equivalent to decomposing the product of two large prime numbers.

RSA has been the most widely used in the world. In the international standard X.509 promulgated by ISO in 1992, it formally incorporated the RSA algorithm into the international standard.

RSA encryption

package main
 
import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"
    "fmt"
    "os"
)
 
 
 
 
// GenerateRSAKey generates RSA private and public keys and saves them to a filefunc GenerateRSAKey(bits int){
    //GenerateKey function uses the random data generator random to generate a pair of RSA keys with a specified number of words    //Reader is a global, shared password generator with strong random number    privateKey, err := (, bits)
    if err!=nil{
        panic(err)
    }
    //Save the private key    //Serialize the obtained ras private key into a DER encoded string of ASN.1 through the x509 standard    // X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey) // PKCS1 and 9 are inconsistent    X509PrivateKey,err := x509.MarshalPKCS8PrivateKey(privateKey)
    if err != nil {
        (())
        (0)
    }
    //Encoding the content output from x509 using pem format    //Create a file and save the private key    privateFile, err := ("")
    if err!=nil{
        panic(err)
    }
    defer ()
    //Construct a structure object    privateBlock:= {Type: "PRIVATE KEY",Bytes:X509PrivateKey}
    //Save data to file    (privateFile,&privateBlock)
    //Save the public key    //Get the public key data    publicKey:=
    //X509 encodes the public key    X509PublicKey,err:=(&publicKey)
    if err!=nil{
        panic(err)
    }
    //pem format encoding    //Create a file to save the public key    publicFile, err := ("")
    if err!=nil{
        panic(err)
    }
    defer ()
    //Create a structure object    publicBlock:= {Type: "Public Key",Bytes:X509PublicKey}
    //Save to file    (publicFile,&publicBlock)
}
 
// RsaEncrypt RSA encryptionfunc RsaEncrypt(plainText []byte,path string)[]byte{
    //Open the file    file,err:=(path)
    if err!=nil{
        panic(err)
    }
    defer ()
    //Read the content of the file    info, _ := ()
    buf:=make([]byte,())
    (buf)
    //pem decoding    block, _ := (buf)
    //x509 decoding    publicKeyInterface, err := ()
    if err!=nil{
        panic(err)
    }
    // Type Assertion    publicKey:=publicKeyInterface.(*)
    //Encrypt the plain text    cipherText, err := rsa.EncryptPKCS1v15(, publicKey, plainText)
    if err!=nil{
        panic(err)
    }
    //Return to the ciphertext    return cipherText
}
 
// RsaDecrypt RSA decryptfunc RsaDecrypt(cipherText []byte,path string) []byte{
    //Open the file    file,err:=(path)
    if err!=nil{
        panic(err)
    }
    defer ()
    //Get the file content    info, _ := ()
    buf:=make([]byte,())
    (buf)
    //pem decoding    block, _ := (buf)
    //X509 decoding    privateKey, err := x509.ParsePKCS8PrivateKey()
    if err!=nil{
        (())
        (0)
    }
    //Decrypt the ciphertext    plainText,_:=rsa.DecryptPKCS1v15(,privateKey.(*),cipherText)
    //Return to the plain text    return plainText
}
 
 
func main(){
    // RSA/ECB/PKCS1Padding
    // RSA is the algorithm, ECB is the block mode, and PKCS1Padding is the fill mode 
    // pkcs1 private key generates openssl genrsa -out 1024    // pkcs1 to pkcs8 private key: openssl pkcs8 -in -nocrypt -out 
    // pkcs1 BEGIN RSA PRIVATE KEY
    // pkcs8 BEGIN PRIVATE KEY
 
    GenerateRSAKey(1024)
    publicPath := "public_key.pem"
    privatePath := "private_key.pem"
 
    publicPath = ""
    privatePath = ""
 
    txt := []byte("hello")
    encrptTxt := RsaEncrypt(txt,publicPath)
    decrptCode := RsaDecrypt(encrptTxt,privatePath)
    (string(decrptCode))
 
}

RSA segment encryption

package main
 
import (
    "bytes"
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/base64"
    "encoding/pem"
    "fmt"
    "log"
    "os"
)
 
func main() {
    GenerateRSAKey(2048)
    publicPath := ""
    privatePath := ""
    var a = []byte("hello")
    encrptTxt, err := RsaEncryptBlock(a, publicPath)
    if err != nil {
        (())
    }
    encodeString := (encrptTxt)
    decodeByte, err := (encodeString)
    if err != nil {
        panic(err)
    }
    //Generate RSA private key and public key and save it to the file    decrptCode := RSA_Decrypts(decodeByte, privatePath)
    (string(decrptCode))
 
}
 
 
func GenerateRSAKey(bits int) {
    //GenerateKey function uses the random data generator random to generate a pair of RSA keys with a specified number of words    //Reader is a global, shared password generator with strong random number    privateKey, err := (, bits)
    if err != nil {
        panic(err)
    }
    //Save the private key    //Serialize the obtained ras private key into a DER encoded string of ASN.1 through the x509 standard    // X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey) // PKCS1 and 9 are inconsistent    X509PrivateKey, err := x509.MarshalPKCS8PrivateKey(privateKey)
    if err != nil {
        (())
        (0)
    }
    //Encoding the content output from x509 using pem format    //Create a file and save the private key    privateFile, err := ("")
    if err != nil {
        panic(err)
    }
    defer ()
    //Construct a structure object    privateBlock := {Type: "PRIVATE KEY", Bytes: X509PrivateKey}
    //Save data to file    (privateFile, &privateBlock)
    //Save the public key    //Get the public key data    publicKey := 
    //X509 encodes the public key    X509PublicKey, err := (&publicKey)
    if err != nil {
        panic(err)
    }
    //pem format encoding    //Create a file to save the public key    publicFile, err := ("")
    if err != nil {
        panic(err)
    }
    defer ()
    //Create a structure object    publicBlock := {Type: "Public Key", Bytes: X509PublicKey}
    //Save to file    (publicFile, &publicBlock)
}
 
// RSA_Decrypts RSA decryption supports segmented decryptionfunc RSA_Decrypts(cipherText []byte, path string) []byte {
    //Open the file    var bytesDecrypt []byte
    file, err := (path)
    if err != nil {
        panic(err)
    }
    defer ()
    //Get the file content    info, _ := ()
    buf := make([]byte, ())
    (buf)
    //pem decoding    block, _ := (buf)
    //X509 decoding    privateKey, err := x509.ParsePKCS8PrivateKey()
    if err != nil {
        (())
        (0)
    }
    p := privateKey.(*)
    keySize := ()
    srcSize := len(cipherText)
    ("Key Length", keySize, "Password Length", srcSize)
    var offSet = 0
    var buffer = {}
    for offSet < srcSize {
        endIndex := offSet + keySize
        if endIndex > srcSize {
            endIndex = srcSize
        }
        bytesOnce, err := rsa.DecryptPKCS1v15(, p, cipherText[offSet:endIndex])
        if err != nil {
            return nil
        }
        (bytesOnce)
        offSet = endIndex
    }
    bytesDecrypt = ()
    return bytesDecrypt
}
 
// RsaEncryptBlock Public Key Encryption-Segmentationfunc RsaEncryptBlock(src []byte, path string) (bytesEncrypt []byte, err error) {
    //Open the file    file, err := (path)
    if err != nil {
        panic(err)
    }
    defer ()
    //Read the content of the file    info, _ := ()
    buf := make([]byte, ())
    (buf)
    //pem decoding    block, _ := (buf)
    //x509 decoding    publicKeyInterface, err := ()
    if err != nil {
        panic(err)
    }
    // Type Assertion    publicKey := publicKeyInterface.(*)
    keySize, srcSize := (), len(src)
    ("Key Length", keySize, "Length of plain text", srcSize)
    offSet, once := 0, keySize-11
    buffer := {}
    for offSet < srcSize {
        endIndex := offSet + once
        if endIndex > srcSize {
            endIndex = srcSize
        }
        // Encrypt part        bytesOnce, err := rsa.EncryptPKCS1v15(, publicKey, src[offSet:endIndex])
        if err != nil {
            return nil, err
        }
        (bytesOnce)
        offSet = endIndex
    }
    bytesEncrypt = ()
    return
}

encryption

DES (Data Encryption) is a symmetric password (FIPS46-3) used in the 1977 US Federal Information Processing Standard (FIPS) cryptography (FIPS46-3). With the advancement of computers, DES has been able to be brute-forced. It took 96 days to decipher the key in DES Challenge I in 1997, 41 days in DES Challenge II-1 in 1998, 56 hours in DES Challenge II-2 in 1998, and only 22 hours and 15 minutes in DES Challenge III in 1999.

DES is a symmetric cryptographic algorithm that encrypts 64-bit plaintext into 64-bit ciphertext, and its key length is 56 bits. Although the key length of the DES is 64 bits in specification, since every 7 bits is set, its key length is essentially 56 bits.

DES is encrypted in a unit of 64-bit plaintext (bit sequence). This 64-bit unit is called packet. Generally speaking, the cipher algorithm processed in units of packets is called packet password. DES is a type of packet password.

DES can only encrypt 64 bits of data at a time. If the plaintext to be encrypted is relatively long, it is necessary to iterate (repeat) the DES encryption, and the specific method of iteration is called the mode.

DES internal implementation theory: In des, each step is called a wheel, and the entire encryption process undergoes 16 cycles.

Built-in library completion

The encryption mode adopts ECB, the filling method adopts pkcs5padding, and the password is "12345678". The output is encoded by hex. You can test it through some online testing tools to see if the results are consistent.

package main
 
import (
    "bytes"
    "crypto/cipher"
    "crypto/des"
    "encoding/hex"
    "fmt"
)
 
func main() {
    data := []byte("hello world")
    key := []byte("12345678")
    iv := []byte("43218765")
 
    result, err := DesCBCEncrypt(data, key, iv)
    if err != nil {
        (err)
    }
    b := (result)
    (b)
}
 
func DesCBCEncrypt(data, key, iv []byte) ([]byte, error) {
    block, err := (key)
    if err != nil {
        return nil, err
    }
 
    data = pkcs5Padding(data, ())
    cryptText := make([]byte, len(data))
 
    blockMode := (block, iv)
    (cryptText, data)
    return cryptText, nil
}
 
func pkcs5Padding(cipherText []byte, blockSize int) []byte {
    padding := blockSize - len(cipherText)%blockSize
    padText := ([]byte{byte(padding)}, padding)
    return append(cipherText, padText...)
}

Using third-party libraries

package main
 
import (
    "fmt"
    "/marspere/goencrypt"
)
 
func main() {
    // key is 12345678    // iv is empty    // Use ECB grouping mode    // Use pkcs5padding fill mode    // The output result is encrypted using base64    cipher := ([]byte("12345678"), []byte(""), , goencrypt.Pkcs7, goencrypt.PrintBase64)
    cipherText, err := ([]byte("hello world"))
    if err != nil {
        (err)
        return
    }
    (cipherText)
}

8.3DES encryption algorithm

3DES (or Triple DES) is the general term for the block password of the Triple Data Encryption Algorithm. It is equivalent to applying a DES encryption algorithm three times to each data block.
Due to the enhanced computing power of computers, the key length of the original DES password has become easily brute-forced; 3DES is designed to provide a relatively simple method, namely, to avoid similar attacks by increasing the key length of the DES, rather than designing a brand new block cipher algorithm.

There is also a library that is very NB

The 3DES algorithm encrypts and decrypts information in ECB mode, golang only provides CBC mode by default

There is a golang encryption library here, which is very powerful

/forgoer/openssl

Install:

go get /thinkoner/openssl

The code is as follows:

package main
 
import (
    "encoding/base64"
    "encoding/hex"
    "fmt"
    "/forgoer/openssl"
)
 
func main() {
 
    //Define the key, it must be 24byte    key := []byte("123456789012345678901234")
    ("Key:", key, (key))
 
    //Definition text    src := []byte("0102030109000000030000000F8898E37A7F8F3D742006111118080000FACE05")
 
    //3DES-ECB encryption    encodeData, _ := openssl.Des3ECBEncrypt(src, key, openssl.ZEROS_PADDING)
    encryptBaseData := (encodeData)
 
    ("Crypto Base64:", encryptBaseData)
    ("Encrypted Hex:", (encodeData))
 
    //3DES-ECB decryption    decodeBaseData, _ := (encryptBaseData)
    decodeData, _ := openssl.Des3ECBDecrypt(decodeBaseData, key, openssl.ZEROS_PADDING)
 
    ("After decryption:", (decodeData))
}

Including Des' encryption and decryption

Here is only one example

srcData := "L0j+JvbeVM0svSpjIwXdE7yTu78wiEszCmW8rwjXY3vrx2nEaUeJ/Rw/c/IRdlxIH+/ro4pykx6ESOkGU1YwM8ddEuuoTg5uPsqQ9/SuNds="
key := []byte("Ctpsp@884*"[:8])
//3DES-ECB decryptiondecodeBaseData, _ := (srcData)
decodeData, _ := (decodeBaseData, key, openssl.PKCS5_PADDING)
("After decryption:", string(decodeData))

Source file:/hybpjx/InverseAlgorithm

The above is the detailed summary of common encryption algorithms in Golang. For more information about Golang encryption, please follow my other related articles!