Exemple #1
0
// Encrypt acts like append() but appends an encrypted version of msg to out.
func (r *Ratchet) Encrypt(out, msg []byte) []byte {
	if r.ratchet {
		r.randBytes(r.sendRatchetPrivate[:])
		copy(r.sendHeaderKey[:], r.nextSendHeaderKey[:])

		var sharedKey, keyMaterial [32]byte
		curve25519.ScalarMult(&sharedKey, &r.sendRatchetPrivate, &r.recvRatchetPublic)
		sha := sha256.New()
		sha.Write(rootKeyUpdateLabel)
		sha.Write(r.rootKey[:])
		sha.Write(sharedKey[:])

		if r.v2 {
			sha.Sum(keyMaterial[:0])
			h := hmac.New(sha256.New, keyMaterial[:])
			deriveKey(&r.rootKey, rootKeyLabel, h)
			deriveKey(&r.nextSendHeaderKey, sendHeaderKeyLabel, h)
			deriveKey(&r.sendChainKey, chainKeyLabel, h)
		} else {
			sha.Sum(r.rootKey[:0])
			h := hmac.New(sha256.New, r.rootKey[:])
			deriveKey(&r.nextSendHeaderKey, sendHeaderKeyLabel, h)
			deriveKey(&r.sendChainKey, chainKeyLabel, h)
		}
		r.prevSendCount, r.sendCount = r.sendCount, 0
		r.ratchet = false
	}

	h := hmac.New(sha256.New, r.sendChainKey[:])
	var messageKey [32]byte
	deriveKey(&messageKey, messageKeyLabel, h)
	deriveKey(&r.sendChainKey, chainKeyStepLabel, h)

	var sendRatchetPublic [32]byte
	curve25519.ScalarBaseMult(&sendRatchetPublic, &r.sendRatchetPrivate)
	var header [headerSize]byte
	var headerNonce, messageNonce [24]byte
	r.randBytes(headerNonce[:])
	r.randBytes(messageNonce[:])

	binary.LittleEndian.PutUint32(header[0:4], r.sendCount)
	binary.LittleEndian.PutUint32(header[4:8], r.prevSendCount)
	copy(header[8:], sendRatchetPublic[:])
	copy(header[nonceInHeaderOffset:], messageNonce[:])
	out = append(out, headerNonce[:]...)
	out = secretbox.Seal(out, header[:], &headerNonce, &r.sendHeaderKey)
	r.sendCount++
	return secretbox.Seal(out, msg, &messageNonce, &messageKey)
}
Exemple #2
0
func sealBox(data []byte, key *secretkey.Key) []byte {
	var nonce [24]byte
	if _, err := rand.Read(nonce[:]); err != nil {
		panic("rand.Read error: " + err.Error())
	}
	return secretbox.Seal(nonce[:], data, &nonce, (*[32]byte)(key))
}
Exemple #3
0
func (b *EncryptBackend) Put(hash string, rawData []byte) (err error) {
	// #blobstash/secretbox\n
	// data hash\n
	// data
	var nonce [24]byte
	//out := make([]byte, len(data) + secretbox.Overhead + 24 + headerSize)
	if err := GenerateNonce(&nonce); err != nil {
		return err
	}
	// First we compress the data with snappy
	data := snappy.Encode(nil, rawData)

	var out bytes.Buffer
	out.WriteString("#blobstash/secretbox\n")
	out.WriteString(fmt.Sprintf("%v\n", hash))
	encData := make([]byte, len(data)+secretbox.Overhead)
	secretbox.Seal(encData[0:0], data, &nonce, b.key)
	out.Write(nonce[:])
	out.Write(encData)
	encHash := fmt.Sprintf("%x", blake2b.Sum256(out.Bytes()))
	b.dest.Put(encHash, out.Bytes())
	b.Lock()
	b.index[hash] = encHash
	defer b.Unlock()
	blobsUploaded.Add(b.dest.String(), 1)
	bytesUploaded.Add(b.dest.String(), int64(len(out.Bytes())))
	return
}
Exemple #4
0
// Set encodes a session from v into a cookie on w.
// See encoding/json for encoding behavior.
func Set(w http.ResponseWriter, v interface{}, config *Config) error {
	now := time.Now()
	b, err := json.Marshal(v)
	if err != nil {
		return err
	}
	tb := make([]byte, len(b)+8)
	binary.BigEndian.PutUint64(tb, uint64(now.Unix()))
	copy(tb[8:], b)
	var nonce [24]byte
	_, err = rand.Read(nonce[:])
	if err != nil {
		return err
	}
	out := secretbox.Seal(nonce[:], tb, &nonce, config.Keys[0])
	cookie := &http.Cookie{
		Name:     config.name(),
		Value:    base64.URLEncoding.EncodeToString(out),
		Expires:  now.Add(config.maxAge()),
		Path:     config.Path,
		Domain:   config.Domain,
		Secure:   config.Secure,
		HttpOnly: config.HTTPOnly,
	}
	if cookie.Path == "" {
		cookie.Path = "/"
	}
	s := cookie.String()
	if len(s) > maxSize {
		return ErrTooLong
	}
	w.Header().Add("Set-Cookie", s)
	return nil
}
Exemple #5
0
// Encrypt encrypt the text using a plaintext key
func (k *Kms) Encrypt(plaintext []byte) ([]byte, error) {
	encKey, err := k.generateEnvelopKey(getKey())
	var key [keyLength]byte
	copy(key[:], encKey.Plaintext[0:keyLength])

	rand, err := k.generateNonce()
	if err != nil {
		return nil, err
	}
	var nonce [nonceLength]byte
	copy(nonce[:], rand[0:nonceLength])

	var enc []byte
	enc = secretbox.Seal(enc, plaintext, &nonce, &key)

	ev := &Envelope{
		Ciphertext:   enc,
		EncryptedKey: encKey.CiphertextBlob,
		Nonce:        nonce[:],
	}
	output, err := marshalJSON(ev)
	if err != nil {
		return nil, err
	}
	return output, nil
}
Exemple #6
0
func (s *secretBox) Encrypt(key *[32]byte, data []byte) ([]byte, error) {
	var nonce [24]byte
	if _, err := rand.Read(nonce[:]); err != nil {
		return nil, err
	}
	return secretbox.Seal(nonce[:], data, &nonce, key), nil
}
Exemple #7
0
func (es *encryptStream) encryptBytes(b []byte) error {

	if err := es.numBlocks.check(); err != nil {
		return err
	}

	nonce := es.nonce.ForPayloadBox(es.numBlocks)
	ciphertext := secretbox.Seal([]byte{}, b, (*[24]byte)(nonce), (*[32]byte)(&es.payloadKey))
	hash := sha512.Sum512(ciphertext)

	block := EncryptionBlock{
		PayloadCiphertext: ciphertext,
	}

	for _, tagKey := range es.tagKeys {
		hashBox := tagKey.Box(nonce, hash[:])
		authenticator := hashBox[:secretbox.Overhead]
		block.HashAuthenticators = append(block.HashAuthenticators, authenticator)
	}

	if err := es.encoder.Encode(block); err != nil {
		return err
	}

	es.numBlocks++
	return nil
}
Exemple #8
0
// Encrypt some data with a password
//
// This function automatically stretches the password to meet the KeyLength
// requirement, as well as calculate a fresh nonce. The function returns an
// error if the data/password is empty or not enough data is available in
// rand.Reader, otherwise the first value will be the encryption result,
// containing the salt and nonce.
func (b *Boxer) Encrypt(data []byte, password []byte) ([]byte, error) {
	if len(data) == 0 {
		return nil, errors.New("Cannot encrypt zero-length data.")
	}

	if len(password) == 0 {
		return nil, errors.New("Empty passwords are not allowed for encryption.")
	}

	// derive a new encryption key for this message
	key, salt, err := b.DeriveKeyFromPassword(password)
	if err != nil {
		return nil, errors.New("Could not derive encryption key from password: "******"Could not create nonce: " + err.Error())
	}

	// seal the data in a nacl box; the box will have the kd salt and nonce prepended
	box := make([]byte, SaltLength+NonceLength)
	copy(box, salt[:])
	copy(box[SaltLength:], nonce[:])

	// let the magic happen
	box = secretbox.Seal(box, data, nonce, key)

	return box, nil
}
Exemple #9
0
// MarshalJSON implements json.Marshaler interface.
func (s Secret) MarshalJSON() ([]byte, error) {
	nonce := [length]byte{}
	out := []byte{}
	out = secretbox.Seal(out, []byte(s), &nonce, &Key)
	res := append(nonce[:], out...)
	return json.Marshal(res)
}
Exemple #10
0
// Read as per io.Reader
func (fh *encrypter) Read(p []byte) (n int, err error) {
	if fh.err != nil {
		return 0, fh.err
	}
	if fh.bufIndex >= fh.bufSize {
		// Read data
		// FIXME should overlap the reads with a go-routine and 2 buffers?
		readBuf := fh.readBuf[:blockDataSize]
		n, err = io.ReadFull(fh.in, readBuf)
		if err == io.EOF {
			// ReadFull only returns n=0 and EOF
			return fh.finish(io.EOF)
		} else if err == io.ErrUnexpectedEOF {
			// Next read will return EOF
		} else if err != nil {
			return fh.finish(err)
		}
		// Write nonce to start of block
		copy(fh.buf, fh.nonce[:])
		// Encrypt the block using the nonce
		block := fh.buf
		secretbox.Seal(block[:0], readBuf[:n], fh.nonce.pointer(), &fh.c.dataKey)
		fh.bufIndex = 0
		fh.bufSize = blockHeaderSize + n
		fh.nonce.increment()
	}
	n = copy(p, fh.buf[fh.bufIndex:fh.bufSize])
	fh.bufIndex += n
	return n, nil
}
Exemple #11
0
// Send implements TCPSender by sealing and sending the msg as-is.
func (sender *encryptedTCPSender) Send(msg []byte) error {
	sender.Lock()
	defer sender.Unlock()
	encodedMsg := secretbox.Seal(nil, msg, &sender.state.nonce, sender.state.sessionKey)
	sender.state.advance()
	return sender.sender.Send(encodedMsg)
}
Exemple #12
0
// Encode encodes a single frame worth of payload and returns the encoded
// length.  InvalidPayloadLengthError is recoverable, all other errors MUST be
// treated as fatal and the session aborted.
func (encoder *Encoder) Encode(frame, payload []byte) (n int, err error) {
	payloadLen := len(payload)
	if MaximumFramePayloadLength < payloadLen {
		return 0, InvalidPayloadLengthError(payloadLen)
	}
	if len(frame) < payloadLen+FrameOverhead {
		return 0, io.ErrShortBuffer
	}

	// Generate a new nonce.
	var nonce [nonceLength]byte
	if err = encoder.nonce.bytes(&nonce); err != nil {
		return 0, err
	}
	encoder.nonce.counter++

	// Encrypt and MAC payload.
	box := secretbox.Seal(frame[:lengthLength], payload, &nonce, &encoder.key)

	// Obfuscate the length.
	length := uint16(len(box) - lengthLength)
	lengthMask := encoder.drbg.NextBlock()
	length ^= binary.BigEndian.Uint16(lengthMask)
	binary.BigEndian.PutUint16(frame[:2], length)

	// Return the frame.
	return len(box), nil
}
Exemple #13
0
func (s *registrationSuite) sealBox(c *gc.C, nonce, key []byte, message string) []byte {
	var nonceArray [24]byte
	var keyArray [32]byte
	c.Assert(copy(nonceArray[:], nonce), gc.Equals, len(nonceArray))
	c.Assert(copy(keyArray[:], key), gc.Equals, len(keyArray))
	return secretbox.Seal(nil, []byte(message), &nonceArray, &keyArray)
}
func (pes *testEncryptStream) encryptBytes(b []byte) error {

	if err := pes.numBlocks.check(); err != nil {
		return err
	}

	nonce := pes.numBlocks.newCounterNonce()

	if pes.options.corruptNonce != nil {
		pes.options.corruptNonce(nonce, pes.numBlocks)
	}

	ciphertext := secretbox.Seal([]byte{}, b, (*[24]byte)(nonce), (*[32]byte)(&pes.sessionKey))
	// Compute the MAC over the nonce and the ciphertext
	sum := hashNonceAndAuthTag(nonce, ciphertext)
	macs := pes.macForAllGroups(sum)
	block := EncryptionBlock{
		Version:    PacketVersion1,
		Tag:        PacketTagEncryptionBlock,
		Ciphertext: ciphertext,
		MACs:       macs,
	}

	if pes.options.corruptEncryptionBlock != nil {
		pes.options.corruptEncryptionBlock(&block, pes.numBlocks)
	}

	if err := encodeNewPacket(pes.output, block); err != nil {
		return nil
	}

	pes.numBlocks++
	return nil
}
Exemple #15
0
// LockUnsafe Allow an application  to store config with default/no password.
func LockUnsafe(path string, configbytes []byte, key []byte) (n int, err error) {
	fmt.Printf("Writing %v bytes to %s\n", len(configbytes), path)
	if configbytes == nil {
		return 0, errors.New("seconf: No bytes to write")
	}

	if path == "" {
		return 0, errors.New("seconf: Path can't be blank")
	}

	key = append(key, pad...)
	naclKey := new([keySize]byte)
	copy(naclKey[:], key[:keySize])
	nonce := new([nonceSize]byte)
	// Read bytes from random and put them in nonce until it is full.
	_, err = io.ReadFull(rand.Reader, nonce[:])
	if err != nil {
		return 0, errors.New("Could not read from random: " + err.Error())
	}
	out := make([]byte, nonceSize)
	copy(out, nonce[:])
	out = secretbox.Seal(out, configbytes, nonce, naclKey)

	err = ioutil.WriteFile(path, out, 0600)
	if err != nil {
		return 0, errors.New("Error while writing config file: " + err.Error())
	}

	return len(out), nil
}
// Writes encrypted frames of `sealedFrameSize`
// CONTRACT: data smaller than dataMaxSize is read atomically.
func (sc *SecretConnection) Write(data []byte) (n int, err error) {
	for 0 < len(data) {
		var frame []byte = make([]byte, totalFrameSize)
		var chunk []byte
		if dataMaxSize < len(data) {
			chunk = data[:dataMaxSize]
			data = data[dataMaxSize:]
		} else {
			chunk = data
			data = nil
		}
		chunkLength := len(chunk)
		binary.BigEndian.PutUint16(frame, uint16(chunkLength))
		copy(frame[dataLenSize:], chunk)

		// encrypt the frame
		var sealedFrame = make([]byte, sealedFrameSize)
		secretbox.Seal(sealedFrame[:0], frame, sc.sendNonce, sc.shrSecret)
		// fmt.Printf("secretbox.Seal(sealed:%X,sendNonce:%X,shrSecret:%X\n", sealedFrame, sc.sendNonce, sc.shrSecret)
		incr2Nonce(sc.sendNonce)
		// end encryption

		_, err := sc.conn.Write(sealedFrame)
		if err != nil {
			return n, err
		} else {
			n += len(chunk)
		}
	}
	return
}
Exemple #17
0
func (s *RegisterSuite) seal(c *gc.C, message, key, nonce []byte) []byte {
	var keyArray [32]byte
	var nonceArray [24]byte
	c.Assert(copy(keyArray[:], key), gc.Equals, len(keyArray))
	c.Assert(copy(nonceArray[:], nonce), gc.Equals, len(nonceArray))
	return secretbox.Seal(nil, message, &nonceArray, &keyArray)
}
Exemple #18
0
func (es *encryptStream) encryptBytes(b []byte) error {

	if err := es.numBlocks.check(); err != nil {
		return err
	}

	nonce := nonceForChunkSecretBox(es.numBlocks)
	ciphertext := secretbox.Seal([]byte{}, b, (*[24]byte)(nonce), (*[32]byte)(&es.payloadKey))

	block := encryptionBlock{
		PayloadCiphertext: ciphertext,
	}

	// Compute the digest to authenticate, and authenticate it for each
	// recipient.
	hashToAuthenticate := computePayloadHash(es.headerHash, nonce, ciphertext)
	for _, macKey := range es.macKeys {
		authenticator := hmacSHA512256(macKey, hashToAuthenticate)
		block.HashAuthenticators = append(block.HashAuthenticators, authenticator)
	}

	if err := es.encoder.Encode(block); err != nil {
		return err
	}

	es.numBlocks++
	return nil
}
Exemple #19
0
// Encrypt encrypts a message and returns the encrypted msg (nonce + ciphertext).
// If you have enabled compression, it will compress the msg before encrypting it.
func (c SaltSecret) Encrypt(msg []byte) (out []byte, e error) {
	nonce := new([nonceSize]byte)
	_, err := io.ReadFull(rand.Reader, nonce[:])
	if err != nil {
		return nil, err
	}

	// We use the last bit of the nonce as a compression indicator.
	// This should still keep you safe (extremely rare collisions).
	nonce[23] &= ^compressBit
	if c.compress {
		nonce[23] |= compressBit
	}

	key, err := scrypt.Key(c.key, nonce[:], 2<<c.NPow, 8, 1, keySize)
	if err != nil {
		return nil, err
	}

	if c.compress {
		var b bytes.Buffer
		w := zlib.NewWriter(&b)
		w.Write(msg)
		w.Close()
		msg = b.Bytes()
	}

	out = make([]byte, nonceSize)
	copy(out, nonce[:])
	naclKey := new([keySize]byte)
	copy(naclKey[:], key)
	out = secretbox.Seal(out, msg, nonce, naclKey)
	return out, nil
}
Exemple #20
0
func (kx *KeyExchange) exchange1() error {
	reply, err := kx.meetingPlace.Exchange(kx.Log, kx.meeting1[:], kx.message1[:], kx.ShutdownChan)
	if err != nil {
		return err
	}

	var peerDHPublic, encryptedPeerDHPublic [32]byte
	if len(reply) < len(encryptedPeerDHPublic) {
		return errors.New("panda: meeting point reply too small")
	}

	copy(encryptedPeerDHPublic[:], reply)
	rijndael.NewCipher(&kx.key).Decrypt(&peerDHPublic, &encryptedPeerDHPublic)

	curve25519.ScalarMult(&kx.sharedKey, &kx.dhPrivate, &peerDHPublic)

	paddedLen := kx.meetingPlace.Padding()
	padded := make([]byte, paddedLen-24 /* nonce */ -secretbox.Overhead)
	binary.LittleEndian.PutUint32(padded, uint32(len(kx.kxBytes)))
	copy(padded[4:], kx.kxBytes)
	if _, err := io.ReadFull(kx.rand, padded[4+len(kx.kxBytes):]); err != nil {
		return err
	}

	var nonce [24]byte
	if _, err := io.ReadFull(kx.rand, nonce[:]); err != nil {
		return err
	}

	kx.message2 = make([]byte, paddedLen)
	copy(kx.message2, nonce[:])
	secretbox.Seal(kx.message2[24:24], padded, &nonce, &kx.sharedKey)

	return nil
}
Exemple #21
0
// Encrypt returns ciphertext from plaintext
func Encrypt(key *[KeySize]byte, nonce *[NonceSize]byte, plaintext []byte) ([]byte, error) {
	ciphertext := make([]byte, len(nonce))
	copy(ciphertext, nonce[:])
	ciphertext = secretbox.Seal(ciphertext, plaintext, nonce, key)

	return ciphertext, nil
}
Exemple #22
0
func (c *Crypt) Encrypt(keyArn string, dec []byte) ([]byte, error) {
	req := &kms.GenerateDataKeyInput{
		KeyId:         aws.String(keyArn),
		NumberOfBytes: aws.Int64(KeyLength),
	}

	res, err := KMS(c).GenerateDataKey(req)

	if err != nil {
		return nil, err
	}

	var key [KeyLength]byte
	copy(key[:], res.Plaintext[0:KeyLength])

	rand, err := c.generateNonce()

	if err != nil {
		return nil, err
	}

	var nonce [NonceLength]byte
	copy(nonce[:], rand[0:NonceLength])

	var enc []byte
	enc = secretbox.Seal(enc, dec, &nonce, &key)

	e := &Envelope{
		Ciphertext:   enc,
		EncryptedKey: res.CiphertextBlob,
		Nonce:        nonce[:],
	}

	return json.Marshal(e)
}
Exemple #23
0
func encryptError(info []byte) []byte {
	out := []byte{18, 147, 175, 43}
	var nonce [24]byte
	rand.Read(nonce[:])
	out = append(out, nonce[:]...)
	out = secretbox.Seal(out, info, &nonce, &ErrorEncryptionKey)
	return out
}
// Encrypts the key with the master key.
// Requires the master key to be unsealed.
func (k *Key) Encrypt() {
	defer Zero(k.raw[:])
	k.Key = secretbox.Seal(
		nil,
		k.raw[:],
		k.nonce(),
		master)
}
Exemple #25
0
// Encrypt encrypts the plaintext message given the key associated with the Crypto object and
// returns the encrypted output.
func (ic *Crypto) Encrypt(message string) string {
	var nonce [24]byte
	rand.Reader.Read(nonce[:]) // should check that you actually read in practice

	var encrypted []byte
	encrypted = secretbox.Seal(encrypted, []byte(message), &nonce, &ic.key)
	return base64.StdEncoding.EncodeToString(encrypted) + "@" + base64.StdEncoding.EncodeToString(nonce[:])
}
Exemple #26
0
func (s *Convergent) Put(key []byte, value []byte) error {
	nonce := s.makeNonce(key)
	box := secretbox.Seal(nil, value, nonce, s.secret)

	boxedkey := s.computeBoxedKey(key)
	err := s.untrusted.Put(boxedkey, box)
	return err
}
Exemple #27
0
// SaveConfig saves configuration file.
// if configKey has been set, the file will be encrypted.
func SaveConfig() {
	if len(configKey) == 0 {
		err := goconfig.SaveConfigFile(configData, ConfigPath)
		if err != nil {
			log.Fatalf("Failed to save config file: %v", err)
		}
		err = os.Chmod(ConfigPath, 0600)
		if err != nil {
			ErrorLog(nil, "Failed to set permissions on config file: %v", err)
		}
		return
	}
	var buf bytes.Buffer
	err := goconfig.SaveConfigData(configData, &buf)
	if err != nil {
		log.Fatalf("Failed to save config file: %v", err)
	}

	f, err := os.Create(ConfigPath)
	if err != nil {
		log.Fatalf("Failed to save config file: %v", err)
	}

	fmt.Fprintln(f, "# Encrypted rclone configuration File")
	fmt.Fprintln(f, "")
	fmt.Fprintln(f, "RCLONE_ENCRYPT_V0:")

	// Generate new nonce and write it to the start of the ciphertext
	var nonce [24]byte
	n, _ := rand.Read(nonce[:])
	if n != 24 {
		log.Fatalf("nonce short read: %d", n)
	}
	enc := base64.NewEncoder(base64.StdEncoding, f)
	_, err = enc.Write(nonce[:])
	if err != nil {
		log.Fatalf("Failed to write config file: %v", err)
	}

	var key [32]byte
	copy(key[:], configKey[:32])

	b := secretbox.Seal(nil, buf.Bytes(), &nonce, &key)
	_, err = enc.Write(b)
	if err != nil {
		log.Fatalf("Failed to write config file: %v", err)
	}
	_ = enc.Close()
	err = f.Close()
	if err != nil {
		log.Fatalf("Failed to close config file: %v", err)
	}

	err = os.Chmod(ConfigPath, 0600)
	if err != nil {
		ErrorLog(nil, "Failed to set permissions on config file: %v", err)
	}
}
Exemple #28
0
func (w *Writer) saveBlock() error {
	// Calculate hash of uncompressed data for ref.
	ref := calculateRef(w.h, w.buf[:w.n])

	//TODO check if this block exists on disk.
	if blockExistsOnDisk(ref) {
		// Append ref to list.
		w.refs = append(w.refs, ref)
		w.n = 0
		w.blockCount++
		return nil
	}

	// Compress.
	compressedData, err := snappy.Encode(w.cdata[headerSize:], w.buf[:w.n])
	if err != nil {
		return err
	}
	dataLen := headerSize + len(compressedData)

	// Pad with zeroes so that the encrypted box is multiple of PadSize.
	var paddedLen int
	if dataLen == 0 {
		paddedLen = PadSize - nonceSize - secretbox.Overhead
	} else {
		paddedLen = (((dataLen + nonceSize + secretbox.Overhead) + (PadSize - 1)) / PadSize) * PadSize
		paddedLen -= nonceSize + secretbox.Overhead
	}
	for i := dataLen; i < paddedLen; i++ {
		w.cdata[i] = 0
	}
	plainBlock := w.cdata[:paddedLen]

	// Set block kind.
	plainBlock[0] = w.kind
	// Store compressed length.
	binary.BigEndian.PutUint32(plainBlock[1:], uint32(len(compressedData)))

	// Encrypt.
	var nonce [24]byte
	if err := generateNonce(&nonce); err != nil {
		return err
	}
	//TODO avoid allocation
	fullBox := make([]byte, len(nonce)+len(plainBlock)+secretbox.Overhead)
	copy(fullBox, nonce[:])
	secretbox.Seal(fullBox[len(nonce):len(nonce)], plainBlock, &nonce, &config.Keys.BlockEnc)
	// Save to disk.
	if err := writeBlockToDisk(ref, fullBox); err != nil {
		return err
	}
	// Append ref to list.
	w.refs = append(w.refs, ref)
	w.n = 0
	w.blockCount++
	return nil
}
Exemple #29
0
func encrypt(key *[keyLen]byte, text *[hashLen]byte, r io.Reader) ([]byte, error) {
	nonce, err := newNonce(r)
	if err != nil {
		return nil, err
	}
	out := make([]byte, 0, len(nonce)+secretbox.Overhead+len(text))
	out = append(out, nonce[:]...)
	return secretbox.Seal(out, text[:], nonce, key), nil
}
Exemple #30
0
// Encrypts the given plaintext and returns ciphertext.
func (b *SimpleBox) Encrypt(plain []byte) []byte {
	var nonce [NonceSize]byte
	rand.Reader.Read(nonce[:])

	var box []byte
	box = secretbox.Seal(box[:0], plain, &nonce, b.secretKey)

	return append(nonce[:], box...)
}