forked from ThalesGroup/crypto11
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockmode.go
202 lines (178 loc) · 6.82 KB
/
blockmode.go
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Copyright 2018 Thales e-Security, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package crypto11
import (
"crypto/cipher"
"runtime"
"github.com/miekg/pkcs11"
)
// cipher.BlockMode -----------------------------------------------------
// BlockModeCloser represents a block cipher running in a block-based mode (e.g. CBC).
//
// BlockModeCloser embeds cipher.BlockMode, and can be used as such.
// However, in this case
// (or if the Close() method is not explicitly called for any other reason),
// resources allocated to it may remain live indefinitely.
type BlockModeCloser interface {
cipher.BlockMode
// Close() releases resources associated with the block mode.
Close()
}
const (
modeEncrypt = iota // blockModeCloser is in encrypt mode
modeDecrypt // blockModeCloser is in decrypt mode
)
// NewCBCEncrypter returns a cipher.BlockMode which encrypts in cipher block chaining mode, using the given key.
// The length of iv must be the same as the key's block size.
//
// The new BlockMode acquires persistent resources which are released (eventually) by a finalizer.
// If this is a problem for your application then use NewCBCEncrypterCloser instead.
//
// If that is not possible then adding calls to runtime.GC() may help.
func (key *SecretKey) NewCBCEncrypter(iv []byte) (cipher.BlockMode, error) {
return key.newBlockModeCloser(key.Cipher.CBCMech, modeEncrypt, iv, true)
}
// NewCBCDecrypter returns a cipher.BlockMode which decrypts in cipher block chaining mode, using the given key.
// The length of iv must be the same as the key's block size and must match the iv used to encrypt the data.
//
// The new BlockMode acquires persistent resources which are released (eventually) by a finalizer.
// If this is a problem for your application then use NewCBCDecrypterCloser instead.
//
// If that is not possible then adding calls to runtime.GC() may help.
func (key *SecretKey) NewCBCDecrypter(iv []byte) (cipher.BlockMode, error) {
return key.newBlockModeCloser(key.Cipher.CBCMech, modeDecrypt, iv, true)
}
// NewCBCEncrypterCloser returns a BlockModeCloser which encrypts in cipher block chaining mode, using the given key.
// The length of iv must be the same as the key's block size.
//
// Use of NewCBCEncrypterCloser rather than NewCBCEncrypter represents a commitment to call the Close() method
// of the returned BlockModeCloser.
func (key *SecretKey) NewCBCEncrypterCloser(iv []byte) (BlockModeCloser, error) {
return key.newBlockModeCloser(key.Cipher.CBCMech, modeEncrypt, iv, false)
}
// NewCBCDecrypterCloser returns a BlockModeCloser which decrypts in cipher block chaining mode, using the given key.
// The length of iv must be the same as the key's block size and must match the iv used to encrypt the data.
//
// Use of NewCBCDecrypterCloser rather than NewCBCEncrypter represents a commitment to call the Close() method
// of the returned BlockModeCloser.
func (key *SecretKey) NewCBCDecrypterCloser(iv []byte) (BlockModeCloser, error) {
return key.newBlockModeCloser(key.Cipher.CBCMech, modeDecrypt, iv, false)
}
// blockModeCloser is a concrete implementation of BlockModeCloser supporting CBC.
type blockModeCloser struct {
// PKCS#11 session to use
session *pkcs11Session
// Cipher block size
blockSize int
// modeDecrypt or modeEncrypt
mode int
// Cleanup function
cleanup func()
}
// newBlockModeCloser creates a new blockModeCloser for the chosen mechanism and mode.
func (key *SecretKey) newBlockModeCloser(mech uint, mode int, iv []byte, setFinalizer bool) (*blockModeCloser, error) {
session, err := key.context.getSession()
if err != nil {
return nil, err
}
bmc := &blockModeCloser{
session: session,
blockSize: key.Cipher.BlockSize,
mode: mode,
cleanup: func() {
key.context.pool.Put(session)
},
}
mechDescription := []*pkcs11.Mechanism{pkcs11.NewMechanism(mech, iv)}
switch mode {
case modeDecrypt:
err = session.ctx.DecryptInit(session.handle, mechDescription, key.handle)
case modeEncrypt:
err = session.ctx.EncryptInit(bmc.session.handle, mechDescription, key.handle)
default:
panic("unexpected mode")
}
if err != nil {
bmc.cleanup()
return nil, err
}
if setFinalizer {
runtime.SetFinalizer(bmc, finalizeBlockModeCloser)
}
return bmc, nil
}
func finalizeBlockModeCloser(obj interface{}) {
obj.(*blockModeCloser).Close()
}
func (bmc *blockModeCloser) BlockSize() int {
return bmc.blockSize
}
func (bmc *blockModeCloser) CryptBlocks(dst, src []byte) {
if len(dst) < len(src) {
panic("destination buffer too small")
}
if len(src)%bmc.blockSize != 0 {
panic("input is not a whole number of blocks")
}
var result []byte
var err error
switch bmc.mode {
case modeDecrypt:
result, err = bmc.session.ctx.DecryptUpdate(bmc.session.handle, src)
case modeEncrypt:
result, err = bmc.session.ctx.EncryptUpdate(bmc.session.handle, src)
}
if err != nil {
panic(err)
}
// PKCS#11 2.40 s5.2 says that the operation must produce as much output
// as possible, so we should never have less than we submitted for CBC.
// This could be different for other modes but we don't implement any yet.
if len(result) != len(src) {
panic("nontrivial result from *Final operation")
}
copy(dst[:len(result)], result)
runtime.KeepAlive(bmc)
}
func (bmc *blockModeCloser) Close() {
if bmc.session == nil {
return
}
var result []byte
var err error
switch bmc.mode {
case modeDecrypt:
result, err = bmc.session.ctx.DecryptFinal(bmc.session.handle)
case modeEncrypt:
result, err = bmc.session.ctx.EncryptFinal(bmc.session.handle)
}
bmc.session = nil
bmc.cleanup()
if err != nil {
panic(err)
}
// PKCS#11 2.40 s5.2 says that the operation must produce as much output
// as possible, so we should never have any left over for CBC.
// This could be different for other modes but we don't implement any yet.
if len(result) > 0 {
panic("nontrivial result from *Final operation")
}
}