golang加密算法

发布时间:2024-11-05 18:43:41

Golang加密算法解析 在当今互联网时代,数据的安全性越来越受到重视。为了保护用户的隐私和敏感信息,加密算法成为了一个不可或缺的部分。Golang作为一门强大的编程语言,提供了丰富的加密算法库,使得开发者可以轻松实现各种加密需求。本文将介绍几种常见的Golang加密算法。

对称加密算法

对称加密算法是指加密和解密过程中使用相同的密钥,常见的对称加密算法包括AES、DES和3DES等。Golang通过`crypto/aes`、`crypto/des`等包提供了对称加密算法的实现。

下面是使用AES算法进行加密和解密的示例代码:

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"fmt"
	"io"
)

func encrypt(plainText []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	cipherText := make([]byte, aes.BlockSize+len(plainText))
	iv := cipherText[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(cipherText[aes.BlockSize:], plainText)

	return cipherText, nil
}

func decrypt(cipherText []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	if len(cipherText) < aes.BlockSize {
		return nil, fmt.Errorf("cipherText too short")
	}

	iv := cipherText[:aes.BlockSize]
	cipherText = cipherText[aes.BlockSize:]

	stream := cipher.NewCFBDecrypter(block, iv)
	stream.XORKeyStream(cipherText, cipherText)

	return cipherText, nil
}

func main() {
	key := []byte("1234567890123456")
	plainText := []byte("Hello, World!")

	cipherText, err := encrypt(plainText, key)
	if err != nil {
		fmt.Println(err)
		return
	}

	decryptedText, err := decrypt(cipherText, key)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(decryptedText))
}

非对称加密算法

非对称加密算法是指加密和解密过程中使用不同的密钥,常见的非对称加密算法包括RSA、DSA和ECDSA等。Golang通过`crypto/rsa`、`crypto/dsa`等包提供了非对称加密算法的实现。

下面是使用RSA算法进行加密和解密的示例代码:

package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
)

func encrypt(plainText []byte, publicKeyStr string) ([]byte, error) {
	publicKeyBlock, _ := pem.Decode([]byte(publicKeyStr))
	if publicKeyBlock == nil {
		return nil, fmt.Errorf("failed to parse PEM block containing the public key")
	}

	publicKey, err := x509.ParsePKIXPublicKey(publicKeyBlock.Bytes)
	if err != nil {
		return nil, err
	}

	cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey.(*rsa.PublicKey), plainText)
	if err != nil {
		return nil, err
	}

	return cipherText, nil
}

func decrypt(cipherText []byte, privateKeyStr string) ([]byte, error) {
	privateKeyBlock, _ := pem.Decode([]byte(privateKeyStr))
	if privateKeyBlock == nil {
		return nil, fmt.Errorf("failed to parse PEM block containing the private key")
	}

	privateKey, err := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes)
	if err != nil {
		return nil, err
	}

	plainText, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
	if err != nil {
		return nil, err
	}

	return plainText, nil
}

func main() {
	privateKeyStr := `-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC9rQh0verjRK1FJDhRVqci/5JfKj4uqOTC00Lt8/FNnP3RgbF+
TWOAzh9gQpHV6Hx1+65Lqf5mYMmv4BTXGrYc5HOFrpufhkknpj3j7tLx4JWTLSDk
YgGMnMuL/wNuoxU0S7Xhl37KFeml8RAG98bAwApwYP7u74ibI/uBhHr5wwIDAQAB
AoGACrx9+WzSNaRil8dW8BiOkS6smNQLb+nvW0cmktumADMAoyl30A3zDv+x2heC
ed812sB6kcnctCpUBFB33SWQVqbQNXV/Sxuo03xtEe1QdMBDi2qMBP4ycQE6gzt+
mVKTdfMZSzbfWni76AquOXDXfX/HnmWWmHKYmxXTcHNCZ9ECQQDWYUEOH9vSPvxj
6/BMzNR2yOIFLo5M8rquYxIyrz4V9MnFffojSs97DOjD9dzpTVuZCmd01rCmKe6L
flcmLsDZAkEAygeUbGdrctcrw2EVW1akcR5TQIUKFFrHIGqedCk5KzpNz5twQ/e3
ht54Jt9xCO6fWsm9Tg8GVKKfo6bN++/pdbXKtQJAaPJy/wvUgHwd8toG5bRYLywD
+o7WETpiTp6iNBz4kKEbbECLNLxe842nTeI9nt/HDYw7NRKnKS4OxcvCbQJAZc/J
CTU57EUGZrws5ufa2blhrSUUmGqaZfcMFAK99AbknmlsfOHC/qSm2Dmhtpine7IZ
ua68ExK7UNSEBe209QJAFno6MbdWyyzy6ymDqSB26Ajs/ySm7oqtU8jf0iylQjAb
Gi2GzxyGa40YCHMrr1ohoZzR1N3YYDWf0RJTXVQPSw==
-----END RSA PRIVATE KEY-----`

	publicKeyStr := `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9rQh0verjRK1FJDhRVqci/5Jf
Kj4uqOTC00Lt8/FNnP3RgbF+TWOAzh9gQpHV6Hx1+65Lqf5mYMmv4BTXGrYc5HOF
rpufhkknpj3j7tLx4JWTLSDkYgGMnMuL/wNuoxU0S7Xhl37KFeml8RAG98bAwApw
YP7u74ibI/uBhHr5wwIDAQAB
-----END PUBLIC KEY-----`

	plainText := []byte("Hello, World!")

	cipherText, err := encrypt(plainText, publicKeyStr)
	if err != nil {
		fmt.Println(err)
		return
	}

	decryptedText, err := decrypt(cipherText, privateKeyStr)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(decryptedText))
}

Hash算法

Hash算法是将任意长度的输入消息转换为固定长度的输出摘要,在密码学中被广泛应用。常见的Hash算法包括MD5、SHA-1和SHA-256等。Golang通过`crypto/md5`、`crypto/sha1`和`crypto/sha256`等包提供了Hash算法的实现。

下面是使用SHA-256算法进行Hash的示例代码:

package main

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

func hash(message []byte) string {
	hash := sha256.Sum256(message)
	return hex.EncodeToString(hash[:])
}

func main() {
	message := []byte("Hello, World!")

	fmt.Println(hash(message))
}

总结

相关推荐