2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2017 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
30 "cypherpunks.ru/balloon"
31 "github.com/davecgh/go-xdr/xdr2"
32 "golang.org/x/crypto/blake2b"
36 DefaultS = 1 << 20 / 32
42 MagicNNCPBv2 [8]byte = [8]byte{'N', 'N', 'C', 'P', 'B', 0, 0, 2}
52 MAC *[blake2b.Size256]byte
55 func blake256() hash.Hash {
56 h, err := blake2b.New256(nil)
63 // Create an encrypted blob. sCost -- memory space requirements, number
64 // of hash-output sized (32 bytes) blocks. tCost -- time requirements,
65 // number of rounds. pCost -- number of parallel jobs.
66 func NewEBlob(sCost, tCost, pCost int, password, data []byte) ([]byte, error) {
69 if _, err = rand.Read(salt[:]); err != nil {
72 key := balloon.H(blake256, password, salt[:], sCost, tCost, pCost)
73 kdf, err := blake2b.NewXOF(32+64, key)
77 if _, err = kdf.Write(MagicNNCPBv2[:]); err != nil {
80 keyEnc := new([32]byte)
81 if _, err = io.ReadFull(kdf, keyEnc[:]); err != nil {
84 keyAuth := make([]byte, 64)
85 if _, err = io.ReadFull(kdf, keyAuth); err != nil {
88 mac, err := blake2b.New256(keyAuth)
92 chacha20.XORKeyStream(data, data, new([16]byte), keyEnc)
93 if _, err = mac.Write(data); err != nil {
96 macTag := new([blake2b.Size256]byte)
100 SCost: uint32(sCost),
101 TCost: uint32(tCost),
102 PCost: uint32(pCost),
107 var eblobRaw bytes.Buffer
108 if _, err = xdr.Marshal(&eblobRaw, &eblob); err != nil {
111 return eblobRaw.Bytes(), nil
114 func DeEBlob(eblobRaw, password []byte) ([]byte, error) {
117 if _, err = xdr.Unmarshal(bytes.NewReader(eblobRaw), &eblob); err != nil {
120 if eblob.Magic != MagicNNCPBv2 {
131 kdf, err := blake2b.NewXOF(32+64, key)
135 if _, err = kdf.Write(MagicNNCPBv2[:]); err != nil {
138 keyEnc := new([32]byte)
139 if _, err = io.ReadFull(kdf, keyEnc[:]); err != nil {
142 keyAuth := make([]byte, 64)
143 if _, err = io.ReadFull(kdf, keyAuth); err != nil {
146 mac, err := blake2b.New256(keyAuth)
150 if _, err = mac.Write(eblob.Blob); err != nil {
153 if subtle.ConstantTimeCompare(mac.Sum(nil), eblob.MAC[:]) != 1 {
154 return nil, errors.New("Unauthenticated blob")
156 chacha20.XORKeyStream(eblob.Blob, eblob.Blob, new([16]byte), keyEnc)
157 return eblob.Blob, nil