all repos — safe @ 67378187b415bdee7c5a15a468a0a5829c8306ee

easily encrypt and decrypt in go

safe_test.go (view raw)

 1package safe
 2
 3import (
 4	"testing"
 5)
 6
 7func TestSafeEncryptDecrypt(t *testing.T) {
 8	// Test data
 9	password := "thisis32bitlongpassphraseimusing" // Example 32-byte password
10	plaintext := "This is a secret"
11
12	// Initialize Safe instance with a specific password
13	safe := NewSafe(password)
14
15	// Encrypt plaintext
16	ciphertextHex := safe.Encrypt(plaintext)
17
18	// Decrypt ciphertext
19	decryptedPlaintext, err := safe.Decrypt(ciphertextHex)
20	if err != nil {
21		t.Error(err)
22	}
23
24	// Verify if the decrypted plaintext matches the original plaintext
25	if plaintext != decryptedPlaintext {
26		t.Errorf("Decrypt(Encrypt(%s)) = %s; want %s", plaintext, decryptedPlaintext, plaintext)
27	}
28}
29
30func TestSafeWithRandomPassword(t *testing.T) {
31	// Initialize Safe instance with a random password
32	safe := NewSafe("")
33
34	// Test plaintext
35	plaintext := "Hello, world!"
36
37	// Encrypt plaintext
38	ciphertextHex := safe.Encrypt(plaintext)
39
40	// Decrypt ciphertext
41	decryptedPlaintext, err := safe.Decrypt(ciphertextHex)
42	if err != nil {
43		t.Error(err)
44	}
45
46	// Verify if the decrypted plaintext matches the original plaintext
47	if decryptedPlaintext != plaintext {
48		t.Errorf("Decrypt(Encrypt(%s)) = %s; want %s", plaintext, decryptedPlaintext, plaintext)
49	}
50}
51
52func TestSafeWithBadInput(t *testing.T) {
53	// Test data
54	password := "thisis32bitlongpassphraseimusing" // Example 32-byte password
55	plaintext := "This is a secret"
56
57	// Initialize Safe instance with a specific password
58	safe := NewSafe(password)
59
60	// Encrypt plaintext
61	ciphertextHex := safe.Encrypt(plaintext)
62
63	// Decrypt ciphertext
64	_, err := safe.Decrypt(ciphertextHex + ".")
65	if err == nil {
66		t.Errorf("Decrypt(Encrypt(%s)+\".\") did not return an error", plaintext)
67	}
68}