Skip to content

Commit

Permalink
Add signing and verifying arbitrary bytes (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
mjiang102628 authored Aug 9, 2019
1 parent 6c1b34b commit c0ef626
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
20 changes: 20 additions & 0 deletions crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ var txidPrefix = []byte("TX")
// bidPrefix is prepended to a bid when signing it
var bidPrefix = []byte("aB")

// bytesPrefix is prepended to bytes when signing
var bytesPrefix = []byte("NF")

// RandomBytes fills the passed slice with randomness, and panics if it is
// unable to do so
func RandomBytes(s []byte) {
Expand Down Expand Up @@ -87,6 +90,23 @@ func rawSignTransaction(sk ed25519.PrivateKey, tx types.Transaction) (s types.Si
return
}

// SignBytes signs the bytes and returns the signature
func SignBytes(sk ed25519.PrivateKey, bytesToSign []byte) (signature []byte, err error) {
// prepend the prefix for signing bytes
toBeSigned := bytes.Join([][]byte{bytesPrefix, bytesToSign}, nil)

// sign the bytes
signature = ed25519.Sign(sk, toBeSigned)
return
}

//VerifyBytes verifies that the signature is valid
func VerifyBytes(pk ed25519.PublicKey, message, signature []byte) bool {
msgParts := [][]byte{bytesPrefix, message}
toBeVerified := bytes.Join(msgParts, nil)
return ed25519.Verify(pk, toBeVerified, signature)
}

// SignBid accepts a private key and a bid, and returns the signature of the
// bid under that key
func SignBid(sk ed25519.PrivateKey, bid types.Bid) (signedBid []byte, err error) {
Expand Down
16 changes: 16 additions & 0 deletions crypto/crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/algorand/go-algorand-sdk/encoding/msgpack"
"github.com/algorand/go-algorand-sdk/mnemonic"
"testing"
"math/rand"

"github.com/stretchr/testify/require"
"golang.org/x/crypto/ed25519"
Expand Down Expand Up @@ -116,3 +117,18 @@ func TestMergeMultisigTransactions(t *testing.T) {
expectedTxid := "2U2QKCYSYA3DUJNVP5T2KWBLWVUMX4PPIGN43IPPVGVZKTNFKJFQ"
require.Equal(t, expectedTxid, txid)
}

func TestSignBytes(t *testing.T) {
account := GenerateAccount()
message := make([]byte, 15)
rand.Read(message)
signature, err := SignBytes(account.PrivateKey, message)
require.NoError(t, err)
require.True(t, VerifyBytes(account.PublicKey, message, signature))
if message[0] == 255 {
message[0] = 0
} else {
message[0] = message[0]+1
}
require.False(t, VerifyBytes(account.PublicKey, message, signature))
}

0 comments on commit c0ef626

Please sign in to comment.