1 Star 0 Fork 1

範輝 / tendermint

forked from Gitee 极速下载 / tendermint 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
symmetric.go 1.77 KB
一键复制 编辑 原始数据 按行查看 历史
package xsalsa20symmetric
import (
"errors"
"fmt"
"golang.org/x/crypto/nacl/secretbox"
"github.com/tendermint/tendermint/crypto"
)
// TODO, make this into a struct that implements crypto.Symmetric.
const nonceLen = 24
const secretLen = 32
// secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase))
// The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext.
func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) {
if len(secret) != secretLen {
panic(fmt.Sprintf("Secret must be 32 bytes long, got len %v", len(secret)))
}
nonce := crypto.CRandBytes(nonceLen)
nonceArr := [nonceLen]byte{}
copy(nonceArr[:], nonce)
secretArr := [secretLen]byte{}
copy(secretArr[:], secret)
ciphertext = make([]byte, nonceLen+secretbox.Overhead+len(plaintext))
copy(ciphertext, nonce)
secretbox.Seal(ciphertext[nonceLen:nonceLen], plaintext, &nonceArr, &secretArr)
return ciphertext
}
// secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase))
// The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext.
func DecryptSymmetric(ciphertext []byte, secret []byte) (plaintext []byte, err error) {
if len(secret) != secretLen {
panic(fmt.Sprintf("Secret must be 32 bytes long, got len %v", len(secret)))
}
if len(ciphertext) <= secretbox.Overhead+nonceLen {
return nil, errors.New("Ciphertext is too short")
}
nonce := ciphertext[:nonceLen]
nonceArr := [nonceLen]byte{}
copy(nonceArr[:], nonce)
secretArr := [secretLen]byte{}
copy(secretArr[:], secret)
plaintext = make([]byte, len(ciphertext)-nonceLen-secretbox.Overhead)
_, ok := secretbox.Open(plaintext[:0], ciphertext[nonceLen:], &nonceArr, &secretArr)
if !ok {
return nil, errors.New("Ciphertext decryption failed")
}
return plaintext, nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C/C++
1
https://gitee.com/kt10/tendermint.git
git@gitee.com:kt10/tendermint.git
kt10
tendermint
tendermint
v0.31.12

搜索帮助

Bbcd6f05 5694891 0cc6727d 5694891