2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-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/>.
19 // Package aont stands for All-Or-Nothing-Transform, based on OAEP.
21 // This package implements OAEP (Optimal Asymmetric Encryption Padding)
22 // (http://cseweb.ucsd.edu/~mihir/papers/oaep.html)
23 // used there as All-Or-Nothing-Transformation
24 // (http://theory.lcs.mit.edu/~cis/pubs/rivest/fusion.ps).
25 // We do not fix OAEP parts length, instead we add hash-based
26 // checksum like in SAEP+
27 // (http://crypto.stanford.edu/~dabo/abstracts/saep.html).
29 // AONT takes 128-bit random r, data M to be encoded and produce the
33 // P1 = ChaCha20(key=r, nonce=0x00, 0x00) XOR (M || BLAKE2b(r || M))
34 // P2 = BLAKE2b(P1) XOR r
42 "golang.org/x/crypto/blake2b"
46 // HSize size of generated hash output in terms of OAEP
48 // RSize size of generated random output in terms of OAEP
53 dummyNonce = new([16]byte)
56 // Encode the data, produce AONT package. Data size will be larger than
57 // the original one for 48 bytes.
58 func Encode(r *[RSize]byte, in []byte) ([]byte, error) {
59 out := make([]byte, len(in)+HSize+RSize)
61 h, err := blake2b.New256(nil)
67 copy(out[len(in):], h.Sum(nil))
68 chachaKey := new([32]byte)
69 copy(chachaKey[:], r[:])
70 chacha20.XORKeyStream(out, out, dummyNonce, chachaKey)
72 h.Write(out[:len(in)+32])
73 for i, b := range h.Sum(nil)[:RSize] {
74 out[len(in)+32+i] = b ^ r[i]
79 // Decode the data from AONT package. Data size will be smaller than the
80 // original one for 48 bytes.
81 func Decode(in []byte) ([]byte, error) {
82 if len(in) < HSize+RSize {
83 return nil, errors.New("Too small input buffer")
85 h, err := blake2b.New256(nil)
89 h.Write(in[:len(in)-RSize])
90 chachaKey := new([32]byte)
91 for i, b := range h.Sum(nil)[:RSize] {
92 chachaKey[i] = b ^ in[len(in)-RSize+i]
95 h.Write(chachaKey[:RSize])
96 out := make([]byte, len(in)-RSize)
97 chacha20.XORKeyStream(out, in[:len(in)-RSize], dummyNonce, chachaKey)
98 h.Write(out[:len(out)-HSize])
99 if subtle.ConstantTimeCompare(h.Sum(nil), out[len(out)-HSize:]) != 1 {
100 return nil, errors.New("Invalid checksum")
102 return out[:len(out)-HSize], nil