mirror of
https://github.com/schollz/cowyo.git
synced 2023-08-10 21:13:00 +03:00
Moved the encryption to its own package
This commit is contained in:
28
encrypt/encrypt.go
Normal file
28
encrypt/encrypt.go
Normal file
@ -0,0 +1,28 @@
|
||||
package encrypt
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
|
||||
"github.com/schollz/cryptopasta"
|
||||
)
|
||||
|
||||
func EncryptString(toEncrypt string, password string) (string, error) {
|
||||
key := sha256.Sum256([]byte(password))
|
||||
encrypted, err := cryptopasta.Encrypt([]byte(toEncrypt), &key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hex.EncodeToString(encrypted), nil
|
||||
}
|
||||
|
||||
func DecryptString(toDecrypt string, password string) (string, error) {
|
||||
key := sha256.Sum256([]byte(password))
|
||||
contentData, err := hex.DecodeString(toDecrypt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
bDecrypted, err := cryptopasta.Decrypt(contentData, &key)
|
||||
return string(bDecrypted), err
|
||||
}
|
22
encrypt/encrypt_test.go
Normal file
22
encrypt/encrypt_test.go
Normal file
@ -0,0 +1,22 @@
|
||||
package encrypt
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEncryption(t *testing.T) {
|
||||
s, err := EncryptString("some string", "some password")
|
||||
if err != nil {
|
||||
t.Errorf("What")
|
||||
}
|
||||
d, err := DecryptString(s, "some wrong password")
|
||||
if err == nil {
|
||||
t.Errorf("Should throw error for bad password")
|
||||
}
|
||||
d, err = DecryptString(s, "some password")
|
||||
if err != nil {
|
||||
t.Errorf("Should not throw password")
|
||||
}
|
||||
if d != "some string" {
|
||||
t.Errorf("Problem decoding")
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user