mirror of
				https://github.com/oarkflow/mq.git
				synced 2025-10-31 23:12:32 +08:00 
			
		
		
		
	
		
			
				
	
	
		
			52 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			52 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package codec
 | |
| 
 | |
| import (
 | |
| 	"crypto/aes"
 | |
| 	"crypto/cipher"
 | |
| 	"crypto/hmac"
 | |
| 	"crypto/rand"
 | |
| 	"crypto/sha256"
 | |
| 	"encoding/hex"
 | |
| 	"io"
 | |
| )
 | |
| 
 | |
| func EncryptPayload(key []byte, plaintext []byte) ([]byte, []byte, error) {
 | |
| 	block, err := aes.NewCipher(key)
 | |
| 	if err != nil {
 | |
| 		return nil, nil, err
 | |
| 	}
 | |
| 	aesGCM, err := cipher.NewGCM(block)
 | |
| 	if err != nil {
 | |
| 		return nil, nil, err
 | |
| 	}
 | |
| 	nonce := make([]byte, aesGCM.NonceSize())
 | |
| 	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
 | |
| 		return nil, nil, err
 | |
| 	}
 | |
| 	ciphertext := aesGCM.Seal(nil, nonce, plaintext, nil)
 | |
| 	return ciphertext, nonce, nil
 | |
| }
 | |
| 
 | |
| func DecryptPayload(key []byte, ciphertext []byte, nonce []byte) ([]byte, error) {
 | |
| 	block, err := aes.NewCipher(key)
 | |
| 	if err != nil {
 | |
| 		return nil, err
 | |
| 	}
 | |
| 	aesGCM, err := cipher.NewGCM(block)
 | |
| 	if err != nil {
 | |
| 		return nil, err
 | |
| 	}
 | |
| 	return aesGCM.Open(nil, nonce, ciphertext, nil)
 | |
| }
 | |
| 
 | |
| func CalculateHMAC(key []byte, data []byte) string {
 | |
| 	h := hmac.New(sha256.New, key)
 | |
| 	h.Write(data)
 | |
| 	return hex.EncodeToString(h.Sum(nil))
 | |
| }
 | |
| 
 | |
| func VerifyHMAC(key []byte, data []byte, receivedHMAC string) bool {
 | |
| 	expectedHMAC := CalculateHMAC(key, data)
 | |
| 	return hmac.Equal([]byte(expectedHMAC), []byte(receivedHMAC))
 | |
| }
 | 
