Guest User

Untitled

a guest
Jan 20th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/rand"
  7. "encoding/base64"
  8. "fmt"
  9. "io"
  10. )
  11.  
  12. func main() {
  13. originalText := "encrypt this golang"
  14. fmt.Println(originalText)
  15.  
  16. key := []byte("example key 1234")
  17.  
  18. // encrypt value to base64
  19. cryptoText := encrypt(key, originalText)
  20. fmt.Println(cryptoText)
  21.  
  22. // encrypt base64 crypto to original value
  23. text := decrypt(key, cryptoText)
  24. fmt.Printf(text)
  25. }
  26.  
  27. // encrypt string to base64 crypto using AES
  28. func encrypt(key []byte, text string) string {
  29. // key := []byte(keyText)
  30. plaintext := []byte(text)
  31.  
  32. block, err := aes.NewCipher(key)
  33. if err != nil {
  34. panic(err)
  35. }
  36.  
  37. // The IV needs to be unique, but not secure. Therefore it's common to
  38. // include it at the beginning of the ciphertext.
  39. ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  40. iv := ciphertext[:aes.BlockSize]
  41. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  42. panic(err)
  43. }
  44.  
  45. stream := cipher.NewCFBEncrypter(block, iv)
  46. stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
  47.  
  48. // convert to base64
  49. return base64.URLEncoding.EncodeToString(ciphertext)
  50. }
  51.  
  52. // decrypt from base64 to decrypted string
  53. func decrypt(key []byte, cryptoText string) string {
  54. ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)
  55.  
  56. block, err := aes.NewCipher(key)
  57. if err != nil {
  58. panic(err)
  59. }
  60.  
  61. // The IV needs to be unique, but not secure. Therefore it's common to
  62. // include it at the beginning of the ciphertext.
  63. if len(ciphertext) < aes.BlockSize {
  64. panic("ciphertext too short")
  65. }
  66. iv := ciphertext[:aes.BlockSize]
  67. ciphertext = ciphertext[aes.BlockSize:]
  68.  
  69. stream := cipher.NewCFBDecrypter(block, iv)
  70.  
  71. // XORKeyStream can work in-place if the two arguments are the same.
  72. stream.XORKeyStream(ciphertext, ciphertext)
  73.  
  74. return fmt.Sprintf("%s", ciphertext)
  75. }
Add Comment
Please, Sign In to add comment