-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathrsa.go
336 lines (308 loc) · 10.7 KB
/
rsa.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
//go:build !cmd_go_bootstrap
package openssl
import "C"
import (
"crypto"
"crypto/subtle"
"errors"
"hash"
"runtime"
"unsafe"
)
func GenerateKeyRSA(bits int) (N, E, D, P, Q, Dp, Dq, Qinv BigInt, err error) {
bad := func(e error) (N, E, D, P, Q, Dp, Dq, Qinv BigInt, err error) {
return nil, nil, nil, nil, nil, nil, nil, nil, e
}
pkey, err := generateEVPPKey(_EVP_PKEY_RSA, int32(bits), "")
if err != nil {
return bad(err)
}
defer go_openssl_EVP_PKEY_free(pkey)
switch vMajor {
case 1:
key := go_openssl_EVP_PKEY_get1_RSA(pkey)
if key == nil {
return bad(newOpenSSLError("EVP_PKEY_get1_RSA failed"))
}
defer go_openssl_RSA_free(key)
var n, e, d, p, q, dmp1, dmq1, iqmp _BIGNUM_PTR
go_openssl_RSA_get0_key(key, &n, &e, &d)
go_openssl_RSA_get0_factors(key, &p, &q)
go_openssl_RSA_get0_crt_params(key, &dmp1, &dmq1, &iqmp)
N, E, D = bnToBig(n), bnToBig(e), bnToBig(d)
P, Q = bnToBig(p), bnToBig(q)
Dp, Dq, Qinv = bnToBig(dmp1), bnToBig(dmq1), bnToBig(iqmp)
case 3:
tmp := go_openssl_BN_new()
if tmp == nil {
return bad(newOpenSSLError("BN_new failed"))
}
defer func() {
go_openssl_BN_clear_free(tmp)
}()
var err error
setBigInt := func(bi *BigInt, param cString) bool {
if err != nil {
return false
}
if go_openssl_EVP_PKEY_get_bn_param(pkey, param.ptr(), &tmp) != 1 {
err = newOpenSSLError("EVP_PKEY_get_bn_param failed")
return false
}
*bi = bnToBig(tmp)
go_openssl_BN_clear(tmp)
return true
}
if !(setBigInt(&N, _OSSL_PKEY_PARAM_RSA_N) &&
setBigInt(&E, _OSSL_PKEY_PARAM_RSA_E) &&
setBigInt(&D, _OSSL_PKEY_PARAM_RSA_D) &&
setBigInt(&P, _OSSL_PKEY_PARAM_RSA_FACTOR1) &&
setBigInt(&Q, _OSSL_PKEY_PARAM_RSA_FACTOR2) &&
setBigInt(&Dp, _OSSL_PKEY_PARAM_RSA_EXPONENT1) &&
setBigInt(&Dq, _OSSL_PKEY_PARAM_RSA_EXPONENT2) &&
setBigInt(&Qinv, _OSSL_PKEY_PARAM_RSA_COEFFICIENT1)) {
return bad(err)
}
default:
panic(errUnsupportedVersion())
}
return
}
type PublicKeyRSA struct {
// _pkey MUST NOT be accessed directly. Instead, use the withKey method.
_pkey _EVP_PKEY_PTR
}
func NewPublicKeyRSA(n, e BigInt) (*PublicKeyRSA, error) {
var pkey _EVP_PKEY_PTR
switch vMajor {
case 1:
key := go_openssl_RSA_new()
if key == nil {
return nil, newOpenSSLError("RSA_new failed")
}
if go_openssl_RSA_set0_key(key, bigToBN(n), bigToBN(e), nil) != 1 {
return nil, fail("RSA_set0_key")
}
pkey = go_openssl_EVP_PKEY_new()
if pkey == nil {
go_openssl_RSA_free(key)
return nil, newOpenSSLError("EVP_PKEY_new failed")
}
if go_openssl_EVP_PKEY_assign(pkey, _EVP_PKEY_RSA, (unsafe.Pointer)(key)) != 1 {
go_openssl_RSA_free(key)
go_openssl_EVP_PKEY_free(pkey)
return nil, newOpenSSLError("EVP_PKEY_assign failed")
}
case 3:
var err error
if pkey, err = newRSAKey3(false, n, e, nil, nil, nil, nil, nil, nil); err != nil {
return nil, err
}
default:
panic(errUnsupportedVersion())
}
k := &PublicKeyRSA{_pkey: pkey}
runtime.SetFinalizer(k, (*PublicKeyRSA).finalize)
return k, nil
}
func (k *PublicKeyRSA) finalize() {
go_openssl_EVP_PKEY_free(k._pkey)
}
func (k *PublicKeyRSA) withKey(f func(_EVP_PKEY_PTR) int32) int32 {
// Because of the finalizer, any time _pkey is passed to cgo, that call must
// be followed by a call to runtime.KeepAlive, to make sure k is not
// collected (and finalized) before the cgo call returns.
defer runtime.KeepAlive(k)
return f(k._pkey)
}
type PrivateKeyRSA struct {
// _pkey MUST NOT be accessed directly. Instead, use the withKey method.
_pkey _EVP_PKEY_PTR
}
func NewPrivateKeyRSA(n, e, d, p, q, dp, dq, qinv BigInt) (*PrivateKeyRSA, error) {
var pkey _EVP_PKEY_PTR
switch vMajor {
case 1:
key := go_openssl_RSA_new()
if key == nil {
return nil, newOpenSSLError("RSA_new failed")
}
if go_openssl_RSA_set0_key(key, bigToBN(n), bigToBN(e), bigToBN(d)) != 1 {
return nil, fail("RSA_set0_key")
}
if p != nil && q != nil {
if go_openssl_RSA_set0_factors(key, bigToBN(p), bigToBN(q)) != 1 {
return nil, fail("RSA_set0_factors")
}
}
if dp != nil && dq != nil && qinv != nil {
if go_openssl_RSA_set0_crt_params(key, bigToBN(dp), bigToBN(dq), bigToBN(qinv)) != 1 {
return nil, fail("RSA_set0_crt_params")
}
}
pkey = go_openssl_EVP_PKEY_new()
if pkey == nil {
go_openssl_RSA_free(key)
return nil, newOpenSSLError("EVP_PKEY_new failed")
}
if go_openssl_EVP_PKEY_assign(pkey, _EVP_PKEY_RSA, (unsafe.Pointer)(key)) != 1 {
go_openssl_RSA_free(key)
go_openssl_EVP_PKEY_free(pkey)
return nil, newOpenSSLError("EVP_PKEY_assign failed")
}
case 3:
var err error
if pkey, err = newRSAKey3(true, n, e, d, p, q, dp, dq, qinv); err != nil {
return nil, err
}
default:
panic(errUnsupportedVersion())
}
k := &PrivateKeyRSA{_pkey: pkey}
runtime.SetFinalizer(k, (*PrivateKeyRSA).finalize)
return k, nil
}
func (k *PrivateKeyRSA) finalize() {
go_openssl_EVP_PKEY_free(k._pkey)
}
func (k *PrivateKeyRSA) withKey(f func(_EVP_PKEY_PTR) int32) int32 {
// Because of the finalizer, any time _pkey is passed to cgo, that call must
// be followed by a call to runtime.KeepAlive, to make sure k is not
// collected (and finalized) before the cgo call returns.
defer runtime.KeepAlive(k)
return f(k._pkey)
}
func DecryptRSAOAEP(h, mgfHash hash.Hash, priv *PrivateKeyRSA, ciphertext, label []byte) ([]byte, error) {
return evpDecrypt(priv.withKey, _RSA_PKCS1_OAEP_PADDING, h, mgfHash, label, ciphertext)
}
func EncryptRSAOAEP(h, mgfHash hash.Hash, pub *PublicKeyRSA, msg, label []byte) ([]byte, error) {
return evpEncrypt(pub.withKey, _RSA_PKCS1_OAEP_PADDING, h, mgfHash, label, msg)
}
func DecryptRSAPKCS1(priv *PrivateKeyRSA, ciphertext []byte) ([]byte, error) {
return evpDecrypt(priv.withKey, _RSA_PKCS1_PADDING, nil, nil, nil, ciphertext)
}
func EncryptRSAPKCS1(pub *PublicKeyRSA, msg []byte) ([]byte, error) {
return evpEncrypt(pub.withKey, _RSA_PKCS1_PADDING, nil, nil, nil, msg)
}
func DecryptRSANoPadding(priv *PrivateKeyRSA, ciphertext []byte) ([]byte, error) {
ret, err := evpDecrypt(priv.withKey, _RSA_NO_PADDING, nil, nil, nil, ciphertext)
if err != nil {
return nil, err
}
// We could return here, but the Go standard library test expects DecryptRSANoPadding to verify the result
// in order to defend against errors in the CRT computation.
//
// The following code tries to replicate the verification implemented in the upstream function decryptAndCheck, found at
// https://github.com/golang/go/blob/9de1ac6ac2cad3871760d0aa288f5ca713afd0a6/src/crypto/rsa/rsa.go#L569-L582.
pub := &PublicKeyRSA{_pkey: priv._pkey}
// A private EVP_PKEY can be used as a public key as it contains the public information.
enc, err := EncryptRSANoPadding(pub, ret)
if err != nil {
return nil, err
}
// Upstream does not do a constant time comparison because it works with math/big instead of byte slices,
// and math/big does not support constant-time arithmetic yet. See #20654 for more info.
if subtle.ConstantTimeCompare(ciphertext, enc) != 1 {
return nil, errors.New("rsa: internal error")
}
return ret, nil
}
func EncryptRSANoPadding(pub *PublicKeyRSA, msg []byte) ([]byte, error) {
return evpEncrypt(pub.withKey, _RSA_NO_PADDING, nil, nil, nil, msg)
}
func saltLength(saltLen int, sign bool) (int32, error) {
// A salt length of -2 is valid in OpenSSL, but not in crypto/rsa, so reject
// it, and lengths < -2, before we convert to the OpenSSL sentinel values.
if saltLen <= -2 {
return 0, errors.New("crypto/rsa: invalid PSS salt length")
}
// OpenSSL uses sentinel salt length values like Go crypto does,
// but the values don't fully match for rsa.PSSSaltLengthAuto (0).
if saltLen == 0 {
if sign {
if vMajor == 1 {
// OpenSSL 1.x uses -2 to mean maximal size when signing where Go crypto uses 0.
return _RSA_PSS_SALTLEN_MAX_SIGN, nil
}
// OpenSSL 3.x deprecated RSA_PSS_SALTLEN_MAX_SIGN
// and uses -3 to mean maximal size when signing where Go crypto uses 0.
return _RSA_PSS_SALTLEN_MAX, nil
}
// OpenSSL uses -2 to mean auto-detect size when verifying where Go crypto uses 0.
return _RSA_PSS_SALTLEN_AUTO, nil
}
return int32(saltLen), nil
}
func SignRSAPSS(priv *PrivateKeyRSA, h crypto.Hash, hashed []byte, saltLen int) ([]byte, error) {
cSaltLen, err := saltLength(saltLen, true)
if err != nil {
return nil, err
}
return evpSign(priv.withKey, _RSA_PKCS1_PSS_PADDING, cSaltLen, h, hashed)
}
func VerifyRSAPSS(pub *PublicKeyRSA, h crypto.Hash, hashed, sig []byte, saltLen int) error {
cSaltLen, err := saltLength(saltLen, false)
if err != nil {
return err
}
return evpVerify(pub.withKey, _RSA_PKCS1_PSS_PADDING, cSaltLen, h, sig, hashed)
}
func SignRSAPKCS1v15(priv *PrivateKeyRSA, h crypto.Hash, hashed []byte) ([]byte, error) {
return evpSign(priv.withKey, _RSA_PKCS1_PADDING, 0, h, hashed)
}
func HashSignRSAPKCS1v15(priv *PrivateKeyRSA, h crypto.Hash, msg []byte) ([]byte, error) {
return evpHashSign(priv.withKey, h, msg)
}
func VerifyRSAPKCS1v15(pub *PublicKeyRSA, h crypto.Hash, hashed, sig []byte) error {
if pub.withKey(func(pkey _EVP_PKEY_PTR) int32 {
size := go_openssl_EVP_PKEY_get_size(pkey)
if len(sig) < int(size) {
return 0
}
return 1
}) == 0 {
return errors.New("crypto/rsa: verification error")
}
return evpVerify(pub.withKey, _RSA_PKCS1_PADDING, 0, h, sig, hashed)
}
func HashVerifyRSAPKCS1v15(pub *PublicKeyRSA, h crypto.Hash, msg, sig []byte) error {
return evpHashVerify(pub.withKey, h, msg, sig)
}
func newRSAKey3(isPriv bool, n, e, d, p, q, dp, dq, qinv BigInt) (_EVP_PKEY_PTR, error) {
bld, err := newParamBuilder()
if err != nil {
return nil, err
}
defer bld.finalize()
bld.addBigInt(_OSSL_PKEY_PARAM_RSA_N, n, false)
bld.addBigInt(_OSSL_PKEY_PARAM_RSA_E, e, false)
bld.addBigInt(_OSSL_PKEY_PARAM_RSA_D, d, false)
if p != nil && q != nil {
allPrecomputedExists := dp != nil && dq != nil && qinv != nil
// The precomputed values should only be passed if P and Q are present
// and every precomputed value is present. (If any precomputed value is
// missing, don't pass any of them.)
//
// In OpenSSL 3.0 and 3.1, we must also omit P and Q if any precomputed
// value is missing. See https://github.com/openssl/openssl/pull/22334
if vMinor >= 2 || allPrecomputedExists {
bld.addBigInt(_OSSL_PKEY_PARAM_RSA_FACTOR1, p, true)
bld.addBigInt(_OSSL_PKEY_PARAM_RSA_FACTOR2, q, true)
}
if allPrecomputedExists {
bld.addBigInt(_OSSL_PKEY_PARAM_RSA_EXPONENT1, dp, true)
bld.addBigInt(_OSSL_PKEY_PARAM_RSA_EXPONENT2, dq, true)
bld.addBigInt(_OSSL_PKEY_PARAM_RSA_COEFFICIENT1, qinv, true)
}
}
params, err := bld.build()
if err != nil {
return nil, err
}
defer go_openssl_OSSL_PARAM_free(params)
selection := _EVP_PKEY_PUBLIC_KEY
if isPriv {
selection = _EVP_PKEY_KEYPAIR
}
return newEvpFromParams(_EVP_PKEY_RSA, int32(selection), params)
}