Welcome to mirror list, hosted at ThFree Co, Russian Federation.

mode_ocb2.go « cryptstate « pkg - github.com/mumble-voip/grumble.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1633f72567feb3e9204e99eb7d09706da75dbe48 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (c) 2012 The Grumble Authors
// The use of this source code is goverened by a BSD-style
// license that can be found in the LICENSE-file.

package cryptstate

import (
	"crypto/aes"
	"crypto/cipher"
	"mumble.info/grumble/pkg/cryptstate/ocb2"
)

// ocb2Mode implements the OCB2-AES128 CryptoMode
type ocb2Mode struct {
	cipher cipher.Block
}

// NonceSize returns the nonce size to be used with OCB2-AES128.
func (ocb *ocb2Mode) NonceSize() int {
	return ocb2.NonceSize
}

// KeySize returns the key size to be used with OCB2-AES128.
func (ocb *ocb2Mode) KeySize() int {
	return aes.BlockSize
}

// Overhead returns the overhead that a ciphertext has over a plaintext.
// In the case of OCB2-AES128, the overhead is the authentication tag.
func (ocb *ocb2Mode) Overhead() int {
	return 3
}

// SetKey sets a new key. The key must have a length equal to KeySize().
func (ocb *ocb2Mode) SetKey(key []byte) {
	if len(key) != ocb.KeySize() {
		panic("cryptstate: invalid key length")
	}

	cipher, err := aes.NewCipher(key)
	if err != nil {
		panic("cryptstate: NewCipher returned unexpected " + err.Error())
	}
	ocb.cipher = cipher
}

// Encrypt encrypts a message using OCB2-AES128 and outputs it to dst.
func (ocb *ocb2Mode) Encrypt(dst []byte, src []byte, nonce []byte) {
	if len(dst) <= ocb.Overhead() {
		panic("cryptstate: bad dst")
	}

	tag := dst[0:3]
	dst = dst[3:]
	ocb2.Encrypt(ocb.cipher, dst, src, nonce, tag)
}

// Decrypt decrypts a message using OCB2-AES128 and outputs it to dst.
// Returns false if decryption failed (authentication tag mismatch).
func (ocb *ocb2Mode) Decrypt(dst []byte, src []byte, nonce []byte) bool {
	if len(src) <= ocb.Overhead() {
		panic("cryptstate: bad src")
	}

	tag := src[0:3]
	src = src[3:]
	return ocb2.Decrypt(ocb.cipher, dst, src, nonce, tag)
}