Advertisement
jxsl13

Go/Golang - One Time Pad Encrypt / Decrypt

Nov 15th, 2020
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "errors"
  5. "fmt"
  6. )
  7.  
  8. // otpEncrypt : encrypted = message XOR key
  9. func otpEncrypt(message, key string) ([]byte, error) {
  10.  
  11. msg := []byte(message)
  12. k := []byte(key)
  13.  
  14. if len(msg) > len(k) {
  15. return []byte{}, errors.New("length mismatch")
  16. }
  17.  
  18. result := make([]byte, len(msg))
  19.  
  20. for idx, b := range msg {
  21. keyB := k[idx]
  22.  
  23. result[idx] = b ^ keyB
  24. }
  25. return result, nil
  26. }
  27.  
  28. // otpEncrypt : encrypted = message XOR key
  29. func otpDecrypt(cypher []byte, key string) (message string, err error) {
  30.  
  31. k := []byte(key)
  32.  
  33. if len(cypher) > len(k) {
  34. return "", errors.New("length mismatch")
  35. }
  36.  
  37. result := make([]byte, len(cypher))
  38.  
  39. for idx, b := range cypher {
  40. keyB := k[idx]
  41.  
  42. result[idx] = b ^ keyB
  43. }
  44. return string(result), nil
  45. }
  46.  
  47. func main() {
  48. key := "passw0rd"
  49. cypher, err := otpEncrypt("hallo", key)
  50. fmt.Println(cypher)
  51. if err != nil {
  52. fmt.Printf("Error: %v\n", err)
  53. }
  54.  
  55. msg, err := otpDecrypt(cypher, key)
  56. fmt.Println(msg)
  57. if err != nil {
  58. fmt.Printf("Error: %v\n", err)
  59. }
  60.  
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement