Go语言编程实现Base64加密解密

407 篇文章 ¥29.90 ¥99.00
本文介绍了在Go语言中使用内置包进行Base64加密和解密的操作。详细阐述了如何使用`encoding/base64`包的`EncodeToString`和`MustDecodeFromBytes`函数,提供了示例代码展示加密解密过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Base64是一种常用的编码方式,可以将二进制数据转换为可打印的ASCII字符,常用于数据传输和存储。在Go语言中,我们可以使用内置的encoding/base64包来实现Base64的加密和解密操作。本文将详细介绍如何在Go语言中使用Base64进行加密和解密,并提供相应的源代码示例。

首先,我们需要导入encoding/base64包:

import (
	"encoding/base64"
	"fmt"
)

接下来,我们将介绍Base64的加密和解密操作。

Base64加密

要将数据进行Base64加密,我们可以使用base64.StdEncoding.EncodeToString方法。下面是一个示例代码:

func
是的,对称加密算法可以在不同的编程语言实现,并且可以实现相同的加密解密结果。下面是一个使用Go、Java和JavaScript实现AES对称加密算法的示例代码: Go: ```go package main import ( "crypto/aes" "crypto/cipher" "encoding/base64" "fmt" ) func main() { key := []byte("1234567890123456") plaintext := []byte("Hello, world!") block, _ := aes.NewCipher(key) ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, err := rand.Read(iv); err != nil { panic(err) } stream := cipher.NewCFBEncrypter(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) fmt.Printf("Encrypted: %v\n", base64.URLEncoding.EncodeToString(ciphertext)) } ``` Java: ```java import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class Main { public static void main(String[] args) throws Exception { byte[] key = "1234567890123456".getBytes(); byte[] plaintext = "Hello, world!".getBytes(); KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128, new SecureRandom(key)); byte[] iv = new byte[16]; SecureRandom random = new SecureRandom(); random.nextBytes(iv); SecretKeySpec secretKeySpec = new SecretKeySpec(keyGenerator.generateKey().getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(iv)); byte[] ciphertext = cipher.doFinal(plaintext); System.out.printf("Encrypted: %s\n", Base64.getEncoder().encodeToString(ciphertext)); } } ``` JavaScript: ```javascript const crypto = require('crypto'); const key = Buffer.from('1234567890123456'); const plaintext = Buffer.from('Hello, world!'); const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv('aes-128-cbc', key, iv); let ciphertext = cipher.update(plaintext); ciphertext = Buffer.concat([ciphertext, cipher.final()]); console.log(`Encrypted: ${ciphertext.toString('base64')}`); ``` 这三段代码实现了相同的AES对称加密算法,并且输出的加密结果相同。如果需要解密,可以使用相同的密钥和IV值,以及相同的算法和模式进行解密。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值