温馨提示×

Linux下Golang如何实现数据加密

小樊
40
2025-10-09 21:30:02
栏目: 编程语言

在Linux下使用Golang进行数据加密,你可以使用Go标准库中的"crypto"包。这个包提供了许多加密算法,如AES、DES、RSA等。下面是一个使用AES加密和解密的简单示例:

package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/hex" "fmt" "io" ) func main() {	key := []byte("this is a 16 byte key") // AES-128需要16字节的密钥	plaintext := []byte("Hello, World!") // 加密	ciphertext, err := encrypt(key, plaintext) if err != nil { panic(err)	}	fmt.Printf("Ciphertext: %s\n", hex.EncodeToString(ciphertext)) // 解密	decrypted, err := decrypt(key, ciphertext) if err != nil { panic(err)	}	fmt.Printf("Decrypted: %s\n", decrypted) } func encrypt(key, plaintext []byte) ([]byte, error) {	block, err := aes.NewCipher(key) if err != nil { return nil, err	}	plaintext = pkcs5Padding(plaintext, aes.BlockSize)	ciphertext := make([]byte, len(plaintext))	iv := make([]byte, aes.BlockSize) if _, err := io.ReadFull(rand.Reader, iv); err != nil { return nil, err	}	mode := cipher.NewCBCEncrypter(block, iv)	mode.CryptBlocks(ciphertext, plaintext) return append(iv, ciphertext...), nil } func decrypt(key, ciphertext []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:]	mode := cipher.NewCBCDecrypter(block, iv)	plaintext := make([]byte, len(ciphertext))	mode.CryptBlocks(plaintext, ciphertext)	plaintext = pkcs5UnPadding(plaintext) return plaintext, nil } func pkcs5Padding(src []byte, blockSize int) []byte {	padding := blockSize - len(src)%blockSize	padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(src, padtext...) } func pkcs5UnPadding(src []byte) []byte {	length := len(src)	unpadding := int(src[length-1]) return src[:(length - unpadding)] } 

在这个示例中,我们使用了AES加密算法和CBC模式。首先,我们创建了一个AES密码块,然后对明文进行PKCS5填充以满足块大小要求。接下来,我们生成一个随机的初始化向量(IV),并使用CBC模式进行加密。最后,我们将IV附加到密文的前面,以便在解密时使用。

解密过程与加密过程相反。我们从密文中提取IV,然后使用CBC模式进行解密。最后,我们对解密后的数据进行PKCS5去除填充。

注意:在实际应用中,密钥管理和错误处理非常重要。这个示例仅用于演示目的,不建议在生产环境中使用。

0