Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Migrated bcrypt.GeneratePassword to pdkdf2 and added tests #400

Merged
merged 5 commits into from
Mar 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 41 additions & 13 deletions crypto/armor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package crypto

import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
Expand All @@ -16,6 +17,8 @@ import (
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/crypto/xsalsa20symmetric"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"

pdkdf2 "golang.org/x/crypto/pbkdf2"
)

const (
Expand Down Expand Up @@ -149,13 +152,12 @@ func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase string, algo st
// encrypted priv key.
func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) {
saltBytes = crypto.CRandBytes(16)
key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter)
if err != nil {
panic(errorsmod.Wrap(err, "error generating bcrypt key from passphrase"))
}

key := pdkdf2.Key([]byte(passphrase), saltBytes, int(BcryptSecurityParameter), 60, sha256.New)
key = crypto.Sha256(key) // get 32 bytes

privKeyBytes := legacy.Cdc.MustMarshal(privKey)
privKeyBytesHash := crypto.Sha256(privKeyBytes)
privKeyBytes = append(privKeyBytes, privKeyBytesHash...) // Add own hash to differentiate it from old implementation

return saltBytes, xsalsa20symmetric.EncryptSymmetric(privKeyBytes, key)
}
Expand Down Expand Up @@ -194,21 +196,47 @@ func UnarmorDecryptPrivKey(armorStr string, passphrase string) (privKey cryptoty
}

func decryptPrivKey(saltBytes []byte, encBytes []byte, passphrase string) (privKey cryptotypes.PrivKey, err error) {
key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter)
key := pdkdf2.Key([]byte(passphrase), saltBytes, int(BcryptSecurityParameter), 60, sha256.New)

var privKeyBytes []byte

decryptedPrivBytes, err := decryptSymmetric(encBytes, key)
if err == nil && len(decryptedPrivBytes) > 32 {
privBytes := decryptedPrivBytes[:len(decryptedPrivBytes)-32]
privBytesHash := decryptedPrivBytes[len(decryptedPrivBytes)-32:] // SHA-256 hash is 32 bytes
// If the decrypted hash doesn't match the privateBytes hash, then we are working with the old bcrypt algorithm
if !bytes.Equal(crypto.Sha256(privBytes), privBytesHash) {
privBytes, err = legacyDecryptPrivKey(saltBytes, encBytes, passphrase)
}
privKeyBytes = privBytes
} else {
privKeyBytes, err = legacyDecryptPrivKey(saltBytes, encBytes, passphrase)
}

if err != nil {
return privKey, errorsmod.Wrap(err, "error generating bcrypt key from passphrase")
return privKey, err
}

key = crypto.Sha256(key) // Get 32 bytes
return legacy.PrivKeyFromBytes(privKeyBytes)
}

privKeyBytes, err := xsalsa20symmetric.DecryptSymmetric(encBytes, key)
if err != nil && err == xsalsa20symmetric.ErrCiphertextDecrypt {
return privKey, sdkerrors.ErrWrongPassword
func decryptSymmetric(encBytes []byte, key []byte) (privKeyBytes []byte, err error) {
key = crypto.Sha256(key)
privKeyBytes, err = xsalsa20symmetric.DecryptSymmetric(encBytes, key)
if err != nil && err.Error() == "ciphertext decryption failed" {
return privKeyBytes, sdkerrors.ErrWrongPassword
} else if err != nil {
return privKey, err
return privKeyBytes, err
}
return privKeyBytes, nil
}

return legacy.PrivKeyFromBytes(privKeyBytes)
func legacyDecryptPrivKey(saltBytes []byte, encBytes []byte, passphrase string) (decryptedBytes []byte, err error) {
key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter)
if err != nil {
return decryptedBytes, errorsmod.Wrap(err, "error generating bcrypt key from passphrase")
}
return decryptSymmetric(encBytes, key)
}

//-----------------------------------------------------------------
Expand Down
45 changes: 40 additions & 5 deletions crypto/armor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ package crypto_test

import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"io"
"testing"

cmtcrypto "github.com/cometbft/cometbft/crypto"
"github.com/cometbft/cometbft/crypto/armor"
"github.com/cometbft/cometbft/crypto/xsalsa20symmetric"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
pdkdf2 "golang.org/x/crypto/pbkdf2"

"cosmossdk.io/depinject"
"github.com/cosmos/cosmos-sdk/codec"
Expand Down Expand Up @@ -167,17 +170,16 @@ func TestUnarmorInfoBytesErrors(t *testing.T) {
require.Nil(t, unarmoredBytes)
}

func BenchmarkBcryptGenerateFromPassword(b *testing.B) {
func BenchmarkBcryptPdkdf2(b *testing.B) {
passphrase := []byte("passphrase")
for securityParam := uint32(9); securityParam < 16; securityParam++ {
param := securityParam
b.Run(fmt.Sprintf("benchmark-security-param-%d", param), func(b *testing.B) {
b.Run(fmt.Sprintf("benchmark-security-param-%d", securityParam), func(b *testing.B) {
b.ReportAllocs()
saltBytes := cmtcrypto.CRandBytes(16)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := bcrypt.GenerateFromPassword(saltBytes, passphrase, param)
require.Nil(b, err)
key := pdkdf2.Key(passphrase, saltBytes, int(securityParam), 60, sha256.New)
require.NotNil(b, key)
}
})
}
Expand All @@ -194,3 +196,36 @@ func TestArmor(t *testing.T) {
assert.Equal(t, blockType, blockType2)
assert.Equal(t, data, data2)
}

func TestBcryptLegacyEncryption(t *testing.T) {
privKey := secp256k1.GenPrivKey()
saltBytes := cmtcrypto.CRandBytes(16)
passphrase := "passphrase"

// Old encryption method
key, _ := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), 12) // Legacy Ley gemeratopm
key = cmtcrypto.Sha256(key) // get 32 bytes
privKeyBytes := legacy.Cdc.MustMarshal(privKey)
encBytes := xsalsa20symmetric.EncryptSymmetric(privKeyBytes, key)
header := map[string]string{
"kdf": "bcrypt",
"salt": fmt.Sprintf("%X", saltBytes),
}
armorString := armor.EncodeArmor("TENDERMINT PRIVATE KEY", header, encBytes)

_, _, err := crypto.UnarmorDecryptPrivKey(armorString, "wrongpassphrase")
require.Error(t, err)
decrypted, algo, err := crypto.UnarmorDecryptPrivKey(armorString, passphrase)
require.NoError(t, err)
require.Equal(t, string(hd.Secp256k1Type), algo)
require.True(t, privKey.Equals(decrypted))

// Latest encryption method
armored := crypto.EncryptArmorPrivKey(privKey, passphrase, "")
_, _, err = crypto.UnarmorDecryptPrivKey(armored, "wrongpassphrase")
require.Error(t, err)
decrypted, algo, err = crypto.UnarmorDecryptPrivKey(armored, passphrase)
require.NoError(t, err)
require.Equal(t, string(hd.Secp256k1Type), algo)
require.True(t, privKey.Equals(decrypted))
}
2 changes: 1 addition & 1 deletion server/grpc/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ func (s *IntegrationTestSuite) TestGRPCServer_Reflection() {
// so that we can always assert that given a reflection server it is
// possible to fully query all the methods, without having any context
// on the proto registry
rc := grpcreflect.NewClient(ctx, stub)
rc := grpcreflect.NewClientV1Alpha(ctx, stub)

services, err := rc.ListServices()
s.Require().NoError(err)
Expand Down