Core components of the web application. https://write.as
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.5 KiB

  1. // Package data provides utilities for interacting with database data
  2. // throughout Write.as.
  3. package data
  4. import (
  5. "bytes"
  6. "crypto/rand"
  7. "strings"
  8. "testing"
  9. )
  10. func TestEncDec(t *testing.T) {
  11. // Generate a random key with a valid length
  12. k := make([]byte, keyLen)
  13. _, err := rand.Read(k)
  14. if err != nil {
  15. t.Fatal(err)
  16. }
  17. runEncDec(t, k, "this is my secret message™. 😄", nil)
  18. runEncDec(t, k, "mygreatemailaddress@gmail.com", nil)
  19. }
  20. func TestAuthentication(t *testing.T) {
  21. // Generate a random key with a valid length
  22. k := make([]byte, keyLen)
  23. _, err := rand.Read(k)
  24. if err != nil {
  25. t.Fatal(err)
  26. }
  27. runEncDec(t, k, "mygreatemailaddress@gmail.com", func(c []byte) []byte {
  28. c[0] = 'a'
  29. t.Logf("Modified: %s\n", c)
  30. return c
  31. })
  32. }
  33. func runEncDec(t *testing.T, k []byte, plaintext string, transform func([]byte) []byte) {
  34. t.Logf("Plaintext: %s\n", plaintext)
  35. // Encrypt the data
  36. ciphertext, err := Encrypt(k, plaintext)
  37. if err != nil {
  38. t.Fatal(err)
  39. }
  40. t.Logf("Ciphertext: %s\n", ciphertext)
  41. if transform != nil {
  42. ciphertext = transform(ciphertext)
  43. }
  44. // Decrypt the data
  45. decryptedText, err := Decrypt(k, ciphertext)
  46. if err != nil {
  47. if transform != nil && strings.Contains(err.Error(), "message authentication failed") {
  48. // We modified the ciphertext; make sure we're getting the right error
  49. t.Logf("%v\n", err)
  50. return
  51. }
  52. t.Fatal(err)
  53. }
  54. t.Logf("Decrypted: %s\n", string(decryptedText))
  55. if !bytes.Equal([]byte(plaintext), decryptedText) {
  56. t.Errorf("Plaintext mismatch: got %x vs %x", plaintext, decryptedText)
  57. }
  58. }