Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- /*
- * sender.go
- * Send encrypted data to the network
- * By J. Stuart McMurray
- * Created 20160226
- * Last Modified 20160226
- */
- import (
- "crypto/rand"
- "io"
- "log"
- "net"
- "golang.org/x/crypto/nacl/secretbox"
- )
- /* send sends messages from in to out, encrypting them with the key. If there
- is an error, it will be sent to ec. */
- func send(out *net.IPConn, in io.Reader, key [KEYLEN]byte, ec chan<- error) {
- if err := xmit(out, in, key, roll); nil != err {
- ec <- err
- }
- ec <- nil
- }
- /* roll encrypts a message, and prepends the nonce, puts it in buf, and
- returns buf. */
- func roll(buf, msg []byte, key [KEYLEN]byte) ([]byte, error) {
- /* Reset buffer */
- buf = buf[0:0]
- /* Get a nonce */
- n := nonce()
- /* Put it at the beginning of the message to send */
- for _, v := range n {
- buf = append(buf, v)
- }
- /* Encrypt the message */
- return secretbox.Seal(buf, msg, &n, &key), nil
- }
- /* nonce returns a nonce. The nonce returned will be different for each call
- to nonce. */
- func nonce() [NONCELEN]byte {
- snoncebuf := make([]byte, NONCELEN)
- var n [NONCELEN]byte
- /* Read random bytes */
- _, err := rand.Read(snoncebuf)
- if nil != err {
- log.Fatalf("Rand read: %v", err)
- }
- /* Populate into an array */
- for i, v := range snoncebuf {
- n[i] = v
- }
- return n
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement