Advertisement
FlyFar

sender.go

Jan 20th, 2024
1,135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.31 KB | Cybersecurity | 0 0
  1. package main
  2.  
  3. /*
  4.  * sender.go
  5.  * Send encrypted data to the network
  6.  * By J. Stuart McMurray
  7.  * Created 20160226
  8.  * Last Modified 20160226
  9.  */
  10.  
  11. import (
  12.     "crypto/rand"
  13.     "io"
  14.     "log"
  15.     "net"
  16.  
  17.     "golang.org/x/crypto/nacl/secretbox"
  18. )
  19.  
  20. /* send sends messages from in to out, encrypting them with the key.  If there
  21. is an error, it will be sent to ec. */
  22. func send(out *net.IPConn, in io.Reader, key [KEYLEN]byte, ec chan<- error) {
  23.     if err := xmit(out, in, key, roll); nil != err {
  24.         ec <- err
  25.     }
  26.     ec <- nil
  27. }
  28.  
  29. /* roll encrypts a message, and prepends the nonce, puts it in buf, and
  30. returns buf. */
  31. func roll(buf, msg []byte, key [KEYLEN]byte) ([]byte, error) {
  32.     /* Reset buffer */
  33.     buf = buf[0:0]
  34.     /* Get a nonce */
  35.     n := nonce()
  36.     /* Put it at the beginning of the message to send */
  37.     for _, v := range n {
  38.         buf = append(buf, v)
  39.     }
  40.     /* Encrypt the message */
  41.     return secretbox.Seal(buf, msg, &n, &key), nil
  42. }
  43.  
  44. /* nonce returns a nonce.  The nonce returned will be different for each call
  45. to nonce. */
  46. func nonce() [NONCELEN]byte {
  47.     snoncebuf := make([]byte, NONCELEN)
  48.     var n [NONCELEN]byte
  49.     /* Read random bytes */
  50.     _, err := rand.Read(snoncebuf)
  51.     if nil != err {
  52.         log.Fatalf("Rand read: %v", err)
  53.     }
  54.     /* Populate into an array */
  55.     for i, v := range snoncebuf {
  56.         n[i] = v
  57.     }
  58.     return n
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement