Esempio n. 1
0
func TestBtnEncryptWriter_PartialWrite(t *testing.T) {
	payload := util.RandomBytes(1024 * 1024)

	var b bytes.Buffer
	bew, err := btncrypt.NewWriteCloser(&b, tu.TestCipher(), len(payload))
	if err != nil {
		t.Errorf("Failed to create BtnEncryptWriter: %v", err)
	}

	verifyWrite(t, bew, payload[:3])
	verifyWrite(t, bew, payload[3:1024])
	verifyWrite(t, bew, payload[1024:4096])
	verifyWrite(t, bew, payload[4096:])

	if err := bew.Close(); err != nil {
		t.Errorf("bew.Close failed: %v", err)
	}

	plain, err := btncrypt.Decrypt(tu.TestCipher(), b.Bytes(), len(payload))
	if err != nil {
		t.Errorf("Failed to decrypt: %v", err)
	}

	if !bytes.Equal(payload, plain) {
		t.Errorf("Failed to restore original payload")
	}
}
Esempio n. 2
0
// GenerateNewBlobPath tries to return a new unique blob path.
// Note that this may return an already used blobpath in high contention, although it is highly unlikely it will happen.
func GenerateNewBlobPath(bs RandomAccessBlobStore) (string, error) {
	const MaxTrial = 256
	const BlobPathLen = 16

	for i := 0; i < MaxTrial; i++ {
		randbin := util.RandomBytes(BlobPathLen)
		candidate := hex.EncodeToString(randbin)

		bh, err := bs.Open(candidate, flags.O_RDONLY)
		if err != nil {
			if err == ENOENT {
				return candidate, nil
			}
			return "", err
		}
		seemsNotUsed := bh.Size() == 0
		if err := bh.Close(); err != nil {
			return "", err
		}

		if seemsNotUsed {
			return candidate, nil
		}
	}
	return "", fmt.Errorf("Failed to generate unique blobpath within %d trials", MaxTrial)
}
Esempio n. 3
0
func (f *frameEncryptor) Sync() ([]byte, error) {
	if f.Written() > BtnFrameMaxPayload {
		return nil, fmt.Errorf("frame payload size exceeding max len: %d > %d", f.Written(), BtnFrameMaxPayload)
	}

	nonce := util.RandomBytes(f.c.gcm.NonceSize())

	f.encrypted = f.encrypted[:len(nonce)]
	copy(f.encrypted, nonce)

	f.encrypted = f.c.gcm.Seal(f.encrypted, nonce, f.b.Bytes(), nil)
	if len(f.encrypted) != f.c.EncryptedFrameSize(f.Written()) {
		logger.Panicf(mylog, "EncryptedFrameSize mismatch. expected: %d, actual: %v", f.c.EncryptedFrameSize(f.Written()), len(f.encrypted))
	}
	f.b.Reset()
	return f.encrypted, nil
}
Esempio n. 4
0
func TestEncrypt_Long(t *testing.T) {
	payload := util.RandomBytes(1024 * 1024)

	envelope, err := btncrypt.Encrypt(tu.TestCipher(), payload)
	if err != nil {
		t.Errorf("Failed to encrypt: %v", err)
	}

	plain, err := btncrypt.Decrypt(tu.TestCipher(), envelope, len(payload))
	if err != nil {
		t.Errorf("Failed to decrypt: %v", err)
	}

	if !bytes.Equal(payload, plain) {
		t.Errorf("Failed to restore original payload")
	}
}