// ExportEncrypted encrypts the current state of the key manager with the // specified password and returns it. The salt used as input to PBKDF2 as well // as nonce for input to secretbox are randomly generated. The actual key used // for encryption is derived from the salt and the passphrase using PBKDF2. func (mgr *Manager) ExportEncrypted(pass []byte) ([]byte, error) { plain, err := mgr.ExportPlaintext() if err != nil { return nil, err } var nonce [nonceSize]byte _, err = rand.Read(nonce[:]) if err != nil { return nil, err } salt := make([]byte, saltLength) _, err = rand.Read(salt) if err != nil { return nil, err } ret := make([]byte, nonceSize+saltLength) copy(ret[:nonceSize], nonce[:]) copy(ret[nonceSize:], salt) ret = secretbox.Seal(ret, plain, &nonce, deriveKey(pass, salt)) return ret, nil }
// Encrypt encrypts the passed data. func (ck *CryptoKey) Encrypt(in []byte) ([]byte, error) { var nonce [NonceSize]byte _, err := io.ReadFull(prng, nonce[:]) if err != nil { return nil, err } blob := secretbox.Seal(nil, in, &nonce, (*[KeySize]byte)(ck)) return append(nonce[:], blob...), nil }
// SealAfterPrecomputation performs the same actions as Seal, but takes a // shared key as generated by Precompute. func SealAfterPrecomputation(out, message []byte, nonce *[24]byte, sharedKey *[32]byte) []byte { return secretbox.Seal(out, message, nonce, sharedKey) }
// Seal appends an encrypted and authenticated copy of message to out, which // will be Overhead bytes longer than the original and must not overlap. The // nonce must be unique for each distinct message for a given pair of keys. func Seal(out, message []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) []byte { var sharedKey [32]byte Precompute(&sharedKey, peersPublicKey, privateKey) return secretbox.Seal(out, message, nonce, &sharedKey) }