Skip to content

Commit

Permalink
Adding a Hashing function (#914)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tang8330 authored Sep 19, 2024
1 parent ecf1d2e commit c2a66e9
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/config/snowflake.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package config
import (
"fmt"

"github.com/artie-labs/transfer/lib/crypto"
"github.com/artie-labs/transfer/lib/cryptography"
"github.com/artie-labs/transfer/lib/typing"
"github.com/snowflakedb/gosnowflake"
)
Expand Down Expand Up @@ -39,7 +39,7 @@ func (s Snowflake) ToConfig() (*gosnowflake.Config, error) {
}

if s.PathToPrivateKey != "" {
key, err := crypto.LoadRSAKey(s.PathToPrivateKey)
key, err := cryptography.LoadRSAKey(s.PathToPrivateKey)
if err != nil {
return nil, fmt.Errorf("failed to load private key: %w", err)
}
Expand Down
15 changes: 14 additions & 1 deletion lib/crypto/rsa.go → lib/cryptography/cryptography.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,28 @@
package crypto
package cryptography

import (
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"fmt"
"os"

"github.com/artie-labs/transfer/lib/typing"
)

// HashValue - Hashes a value using SHA256
func HashValue(value any) any {
if value == nil {
return nil
}

hash := sha256.New()
hash.Write([]byte(fmt.Sprint(value)))
return hex.EncodeToString(hash.Sum(nil))
}

func LoadRSAKey(filePath string) (*rsa.PrivateKey, error) {
keyBytes, err := os.ReadFile(filePath)
if err != nil {
Expand Down
34 changes: 34 additions & 0 deletions lib/cryptography/cryptography_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package cryptography

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestHashValue(t *testing.T) {
{
// If we pass nil in, we should get nil out.
assert.Equal(t, nil, HashValue(nil))
}
{
// Pass in an empty string
assert.Equal(t, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", HashValue(""))
}
{
// Pass in a string
assert.Equal(t, "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9", HashValue("hello world"))
}
{
// Value should be deterministic.
for range 50 {
assert.Equal(t, "b9a40320d82075681b2500e38160538e5e912bd8f49c03e87367fe82c1fa35d2", HashValue("dusty the mini aussie"))
}
}
}

func BenchmarkHashValue(b *testing.B) {
for i := 0; i < b.N; i++ {
assert.Equal(b, "b9a40320d82075681b2500e38160538e5e912bd8f49c03e87367fe82c1fa35d2", HashValue("dusty the mini aussie"))
}
}

0 comments on commit c2a66e9

Please sign in to comment.