Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/rand"
  7. "encoding/base64"
  8. "flag"
  9. "fmt"
  10. "io"
  11. )
  12.  
  13. func main() {
  14. k := flag.String("key", "", "AES-256 compatible encryption/decryption key")
  15. t := flag.String("text", "", "The text that should be encrypted/decrypted")
  16. d := flag.Bool("decrypt", false, "Should I decrypt or encrypt (default)")
  17.  
  18. flag.Parse()
  19.  
  20. if k == nil || t == nil || d == nil {
  21. panic("One of the flags is nil")
  22. }
  23.  
  24. key := []byte(*k)
  25. text := []byte(*t)
  26.  
  27. if len(key) < 32 {
  28. panic("Key too short, needs at least 32 bytes")
  29. }
  30.  
  31. c, err := aes.NewCipher(key)
  32. if err != nil {
  33. panic(err)
  34. }
  35.  
  36. gcm, err := cipher.NewGCM(c)
  37. if err != nil {
  38. panic(err)
  39. }
  40.  
  41. if *d { // decrypt
  42. ns := gcm.NonceSize()
  43.  
  44. text, err := base64.StdEncoding.DecodeString(*t)
  45. if err != nil {
  46. panic(err)
  47. }
  48.  
  49. if len(text) < ns {
  50. panic("Invalid text, too short for decryption")
  51. }
  52.  
  53. nonce, ciphertext := text[:ns], text[ns:]
  54. plain, err := gcm.Open(nil, nonce, ciphertext, nil)
  55. if err != nil {
  56. panic(err)
  57. }
  58.  
  59. fmt.Println(string(plain))
  60. } else { // encrypt
  61. nonce := make([]byte, gcm.NonceSize())
  62.  
  63. if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
  64. panic(err)
  65. }
  66.  
  67. fmt.Println(base64.StdEncoding.EncodeToString(gcm.Seal(nonce, nonce, text, nil)))
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement