Skip to content

Instantly share code, notes, and snippets.

@bradrydzewski
Last active August 29, 2015 14:27
Show Gist options
  • Save bradrydzewski/7bf42524aae5a1316df0 to your computer and use it in GitHub Desktop.
Save bradrydzewski/7bf42524aae5a1316df0 to your computer and use it in GitHub Desktop.
Nacl Box encryption, minus authentication
package main
import (
"bytes"
"crypto/rand"
"fmt"
"io"
"golang.org/x/crypto/nacl/box"
)
// empty byte array used to create an empty keypair for authenticating
// encrypted messages. This means we skip the authentication step in
// nacl box's authenticate and decryption process.
var zeroBytes = [32]byte{}
var zeroPub, zeroPriv, _ = box.GenerateKey(bytes.NewReader(zeroBytes[:]))
// nonceSize is the lenth of the nonce.
const nonceSize = 24
// KeySize is the length of the public and private parts
// of the zone and access keys.
const keySize = 32
func main() {
// generate key for repo
pub, priv, err := box.GenerateKey(rand.Reader)
if err != nil {
fmt.Println(err)
}
encrypted := encryptTo((*pub)[:], []byte("BOSCO"))
decrypted := decryptFrom((*priv)[:], encrypted)
fmt.Printf("encrypted %x\n", encrypted)
fmt.Printf("decrypted %s\n", decrypted)
}
func encryptTo(pubkey, plaintext []byte) []byte {
if pubkey == nil || plaintext == nil || len(pubkey) != keySize {
return nil
}
nonce := new([nonceSize]byte)
if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {
panic(err)
}
publicKey := new([keySize]byte)
copy(publicKey[:], pubkey)
buf := nonce[:]
buf = box.Seal(nonce[:], plaintext, nonce, publicKey, zeroPriv)
return buf
}
func decryptFrom(privkey, ciphertext []byte) []byte {
if privkey == nil || ciphertext == nil || len(privkey) != keySize {
return nil
}
nonce := new([nonceSize]byte)
copy(nonce[:], ciphertext[:nonceSize])
privateKey := new([keySize]byte)
copy(privateKey[:], privkey)
plaintext, ok := box.Open(nil, ciphertext[nonceSize:], nonce, zeroPub, privateKey)
if !ok {
return nil
}
return plaintext
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment