mirror of
https://github.com/fluencelabs/tendermint
synced 2025-06-24 18:21:38 +00:00
.circleci
.github
DOCKER
abci
benchmarks
blockchain
cmd
config
consensus
crypto
hkdfchacha20poly1305
merkle
tmhash
CHANGELOG.md
Gopkg.lock
Gopkg.toml
LICENSE
Makefile
README.md
amino.go
armor.go
armor_test.go
doc.go
encode_test.go
example_test.go
hash.go
priv_key.go
priv_key_test.go
pub_key.go
pub_key_test.go
random.go
signature.go
signature_test.go
symmetric.go
symmetric_test.go
version.go
docs
evidence
libs
lite
mempool
networks
node
p2p
privval
proxy
rpc
scripts
state
test
types
version
.editorconfig
.gitignore
CHANGELOG.md
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Gopkg.lock
Gopkg.toml
LICENSE
Makefile
README.md
ROADMAP.md
SECURITY.md
Vagrantfile
appveyor.yml
codecov.yml
docker-compose.yml
52 lines
1.7 KiB
Go
52 lines
1.7 KiB
Go
![]() |
package crypto
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
|
||
|
. "github.com/tendermint/tmlibs/common"
|
||
|
"golang.org/x/crypto/nacl/secretbox"
|
||
|
)
|
||
|
|
||
|
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.
|
||
|
// NOTE: call crypto.MixEntropy() first.
|
||
|
func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) {
|
||
|
if len(secret) != secretLen {
|
||
|
PanicSanity(Fmt("Secret must be 32 bytes long, got len %v", len(secret)))
|
||
|
}
|
||
|
nonce := 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 {
|
||
|
PanicSanity(Fmt("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
|
||
|
}
|