github.com/adnan-c/fabric_e2e_couchdb@v0.6.1-preview.0.20170228180935-21ce6b23cf91/bccsp/pkcs11/impl.go (about) 1 /* 2 Copyright IBM Corp. 2016 All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 package pkcs11 17 18 import ( 19 "crypto/ecdsa" 20 "crypto/elliptic" 21 "crypto/hmac" 22 "crypto/rand" 23 "crypto/rsa" 24 "crypto/sha256" 25 "crypto/sha512" 26 "crypto/x509" 27 "errors" 28 "fmt" 29 "hash" 30 "math/big" 31 32 "github.com/hyperledger/fabric/bccsp" 33 "github.com/hyperledger/fabric/bccsp/utils" 34 "github.com/op/go-logging" 35 "golang.org/x/crypto/sha3" 36 ) 37 38 var ( 39 logger = logging.MustGetLogger("PKCS11_BCCSP") 40 ) 41 42 // NewDefaultSecurityLevel returns a new instance of the software-based BCCSP 43 // at security level 256, hash family SHA2 and using FolderBasedKeyStore as KeyStore. 44 func NewDefaultSecurityLevel(keyStorePath string) (bccsp.BCCSP, error) { 45 ks := &FileBasedKeyStore{} 46 if err := ks.Init(nil, keyStorePath, false); err != nil { 47 return nil, fmt.Errorf("Failed initializing key store [%s]", err) 48 } 49 50 return New(256, "SHA2", ks) 51 } 52 53 // NewDefaultSecurityLevel returns a new instance of the software-based BCCSP 54 // at security level 256, hash family SHA2 and using the passed KeyStore. 55 func NewDefaultSecurityLevelWithKeystore(keyStore bccsp.KeyStore) (bccsp.BCCSP, error) { 56 return New(256, "SHA2", keyStore) 57 } 58 59 // New returns a new instance of the software-based BCCSP 60 // set at the passed security level, hash family and KeyStore. 61 func New(securityLevel int, hashFamily string, keyStore bccsp.KeyStore) (bccsp.BCCSP, error) { 62 // Init config 63 conf := &config{} 64 err := conf.setSecurityLevel(securityLevel, hashFamily) 65 if err != nil { 66 return nil, fmt.Errorf("Failed initializing configuration [%s]", err) 67 } 68 69 // Check KeyStore 70 if keyStore == nil { 71 return nil, errors.New("Invalid bccsp.KeyStore instance. It must be different from nil.") 72 } 73 74 return &impl{conf, keyStore}, nil 75 } 76 77 // SoftwareBasedBCCSP is the software-based implementation of the BCCSP. 78 type impl struct { 79 conf *config 80 ks bccsp.KeyStore 81 } 82 83 // KeyGen generates a key using opts. 84 func (csp *impl) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) { 85 // Validate arguments 86 if opts == nil { 87 return nil, errors.New("Invalid Opts parameter. It must not be nil.") 88 } 89 90 pkcs11Stored := false 91 92 // Parse algorithm 93 switch opts.(type) { 94 case *bccsp.ECDSAKeyGenOpts: 95 ski, pub, err := generateECKey(csp.conf.ellipticCurve, opts.Ephemeral()) 96 if err != nil { 97 return nil, fmt.Errorf("Failed generating ECDSA key [%s]", err) 98 } 99 k = &ecdsaPrivateKey{ski, ecdsaPublicKey{ski, pub}} 100 pkcs11Stored = true 101 102 case *bccsp.ECDSAP256KeyGenOpts: 103 ski, pub, err := generateECKey(oidNamedCurveP256, opts.Ephemeral()) 104 if err != nil { 105 return nil, fmt.Errorf("Failed generating ECDSA P256 key [%s]", err) 106 } 107 108 k = &ecdsaPrivateKey{ski, ecdsaPublicKey{ski, pub}} 109 pkcs11Stored = true 110 111 case *bccsp.ECDSAP384KeyGenOpts: 112 ski, pub, err := generateECKey(oidNamedCurveP384, opts.Ephemeral()) 113 if err != nil { 114 return nil, fmt.Errorf("Failed generating ECDSA P384 key [%s]", err) 115 } 116 117 k = &ecdsaPrivateKey{ski, ecdsaPublicKey{ski, pub}} 118 pkcs11Stored = true 119 120 case *bccsp.AESKeyGenOpts: 121 lowLevelKey, err := GetRandomBytes(csp.conf.aesBitLength) 122 123 if err != nil { 124 return nil, fmt.Errorf("Failed generating AES key [%s]", err) 125 } 126 127 k = &aesPrivateKey{lowLevelKey, false} 128 129 case *bccsp.AES256KeyGenOpts: 130 lowLevelKey, err := GetRandomBytes(32) 131 132 if err != nil { 133 return nil, fmt.Errorf("Failed generating AES 256 key [%s]", err) 134 } 135 136 k = &aesPrivateKey{lowLevelKey, false} 137 138 case *bccsp.AES192KeyGenOpts: 139 lowLevelKey, err := GetRandomBytes(24) 140 141 if err != nil { 142 return nil, fmt.Errorf("Failed generating AES 192 key [%s]", err) 143 } 144 145 k = &aesPrivateKey{lowLevelKey, false} 146 147 case *bccsp.AES128KeyGenOpts: 148 lowLevelKey, err := GetRandomBytes(16) 149 150 if err != nil { 151 return nil, fmt.Errorf("Failed generating AES 128 key [%s]", err) 152 } 153 154 k = &aesPrivateKey{lowLevelKey, false} 155 156 case *bccsp.RSAKeyGenOpts: 157 lowLevelKey, err := rsa.GenerateKey(rand.Reader, csp.conf.rsaBitLength) 158 159 if err != nil { 160 return nil, fmt.Errorf("Failed generating RSA key [%s]", err) 161 } 162 163 k = &rsaPrivateKey{lowLevelKey} 164 165 case *bccsp.RSA1024KeyGenOpts: 166 lowLevelKey, err := rsa.GenerateKey(rand.Reader, 1024) 167 168 if err != nil { 169 return nil, fmt.Errorf("Failed generating RSA 1024 key [%s]", err) 170 } 171 172 k = &rsaPrivateKey{lowLevelKey} 173 174 case *bccsp.RSA2048KeyGenOpts: 175 lowLevelKey, err := rsa.GenerateKey(rand.Reader, 2048) 176 177 if err != nil { 178 return nil, fmt.Errorf("Failed generating RSA 2048 key [%s]", err) 179 } 180 181 k = &rsaPrivateKey{lowLevelKey} 182 183 case *bccsp.RSA3072KeyGenOpts: 184 lowLevelKey, err := rsa.GenerateKey(rand.Reader, 3072) 185 186 if err != nil { 187 return nil, fmt.Errorf("Failed generating RSA 3072 key [%s]", err) 188 } 189 190 k = &rsaPrivateKey{lowLevelKey} 191 192 case *bccsp.RSA4096KeyGenOpts: 193 lowLevelKey, err := rsa.GenerateKey(rand.Reader, 4096) 194 195 if err != nil { 196 return nil, fmt.Errorf("Failed generating RSA 4096 key [%s]", err) 197 } 198 199 k = &rsaPrivateKey{lowLevelKey} 200 201 default: 202 return nil, fmt.Errorf("Unrecognized KeyGenOpts provided [%s]", opts.Algorithm()) 203 } 204 205 // If the key is not Ephemeral, store it. EC Keys now in HSM, no need to store 206 if !pkcs11Stored && !opts.Ephemeral() { 207 // Store the key 208 err = csp.ks.StoreKey(k) 209 if err != nil { 210 return nil, fmt.Errorf("Failed storing key [%s]. [%s]", opts.Algorithm(), err) 211 } 212 } 213 214 return k, nil 215 } 216 217 // KeyDeriv derives a key from k using opts. 218 // The opts argument should be appropriate for the primitive used. 219 func (csp *impl) KeyDeriv(k bccsp.Key, opts bccsp.KeyDerivOpts) (dk bccsp.Key, err error) { 220 // Validate arguments 221 if k == nil { 222 return nil, errors.New("Invalid Key. It must not be nil.") 223 } 224 225 // Derive key 226 switch k.(type) { 227 case *ecdsaPublicKey: 228 // Validate opts 229 if opts == nil { 230 return nil, errors.New("Invalid Opts parameter. It must not be nil.") 231 } 232 233 ecdsaK := k.(*ecdsaPublicKey) 234 235 switch opts.(type) { 236 237 // Re-randomized an ECDSA public key 238 case *bccsp.ECDSAReRandKeyOpts: 239 pubKey := ecdsaK.pub 240 reRandOpts := opts.(*bccsp.ECDSAReRandKeyOpts) 241 tempSK := &ecdsa.PublicKey{ 242 Curve: pubKey.Curve, 243 X: new(big.Int), 244 Y: new(big.Int), 245 } 246 247 var k = new(big.Int).SetBytes(reRandOpts.ExpansionValue()) 248 var one = new(big.Int).SetInt64(1) 249 n := new(big.Int).Sub(pubKey.Params().N, one) 250 k.Mod(k, n) 251 k.Add(k, one) 252 253 // Compute temporary public key 254 tempX, tempY := pubKey.ScalarBaseMult(k.Bytes()) 255 tempSK.X, tempSK.Y = tempSK.Add( 256 pubKey.X, pubKey.Y, 257 tempX, tempY, 258 ) 259 260 // Verify temporary public key is a valid point on the reference curve 261 isOn := tempSK.Curve.IsOnCurve(tempSK.X, tempSK.Y) 262 if !isOn { 263 return nil, errors.New("Failed temporary public key IsOnCurve check.") 264 } 265 266 ecPt := elliptic.Marshal(tempSK.Curve, tempSK.X, tempSK.Y) 267 oid, ok := oidFromNamedCurve(tempSK.Curve) 268 if !ok { 269 return nil, errors.New("Do not know OID for this Curve.") 270 } 271 272 ski, err := importECKey(oid, nil, ecPt, opts.Ephemeral(), isPublicKey) 273 if err != nil { 274 return nil, fmt.Errorf("Failed getting importing EC Public Key [%s]", err) 275 } 276 reRandomizedKey := &ecdsaPublicKey{ski, tempSK} 277 278 return reRandomizedKey, nil 279 280 default: 281 return nil, fmt.Errorf("Unrecognized KeyDerivOpts provided [%s]", opts.Algorithm()) 282 283 } 284 case *ecdsaPrivateKey: 285 // Validate opts 286 if opts == nil { 287 return nil, errors.New("Invalid Opts parameter. It must not be nil.") 288 } 289 290 ecdsaK := k.(*ecdsaPrivateKey) 291 292 switch opts.(type) { 293 294 // Re-randomized an ECDSA private key 295 case *bccsp.ECDSAReRandKeyOpts: 296 reRandOpts := opts.(*bccsp.ECDSAReRandKeyOpts) 297 pubKey := ecdsaK.pub.pub 298 secret := getSecretValue(ecdsaK.ski) 299 if secret == nil { 300 return nil, errors.New("Could not obtain EC Private Key") 301 } 302 bigSecret := new(big.Int).SetBytes(secret) 303 304 tempSK := &ecdsa.PrivateKey{ 305 PublicKey: ecdsa.PublicKey{ 306 Curve: pubKey.Curve, 307 X: new(big.Int), 308 Y: new(big.Int), 309 }, 310 D: new(big.Int), 311 } 312 313 var k = new(big.Int).SetBytes(reRandOpts.ExpansionValue()) 314 var one = new(big.Int).SetInt64(1) 315 n := new(big.Int).Sub(pubKey.Params().N, one) 316 k.Mod(k, n) 317 k.Add(k, one) 318 319 tempSK.D.Add(bigSecret, k) 320 tempSK.D.Mod(tempSK.D, pubKey.Params().N) 321 322 // Compute temporary public key 323 tempSK.PublicKey.X, tempSK.PublicKey.Y = pubKey.ScalarBaseMult(tempSK.D.Bytes()) 324 325 // Verify temporary public key is a valid point on the reference curve 326 isOn := tempSK.Curve.IsOnCurve(tempSK.PublicKey.X, tempSK.PublicKey.Y) 327 if !isOn { 328 return nil, errors.New("Failed temporary public key IsOnCurve check.") 329 } 330 331 ecPt := elliptic.Marshal(tempSK.Curve, tempSK.X, tempSK.Y) 332 oid, ok := oidFromNamedCurve(tempSK.Curve) 333 if !ok { 334 return nil, errors.New("Do not know OID for this Curve.") 335 } 336 337 ski, err := importECKey(oid, tempSK.D.Bytes(), ecPt, opts.Ephemeral(), isPrivateKey) 338 if err != nil { 339 return nil, fmt.Errorf("Failed getting importing EC Public Key [%s]", err) 340 } 341 reRandomizedKey := &ecdsaPrivateKey{ski, ecdsaPublicKey{ski, &tempSK.PublicKey}} 342 343 return reRandomizedKey, nil 344 345 default: 346 return nil, fmt.Errorf("Unrecognized KeyDerivOpts provided [%s]", opts.Algorithm()) 347 348 } 349 case *aesPrivateKey: 350 // Validate opts 351 if opts == nil { 352 return nil, errors.New("Invalid Opts parameter. It must not be nil.") 353 } 354 355 aesK := k.(*aesPrivateKey) 356 357 switch opts.(type) { 358 case *bccsp.HMACTruncated256AESDeriveKeyOpts: 359 hmacOpts := opts.(*bccsp.HMACTruncated256AESDeriveKeyOpts) 360 361 mac := hmac.New(csp.conf.hashFunction, aesK.privKey) 362 mac.Write(hmacOpts.Argument()) 363 hmacedKey := &aesPrivateKey{mac.Sum(nil)[:csp.conf.aesBitLength], false} 364 365 // If the key is not Ephemeral, store it. 366 if !opts.Ephemeral() { 367 // Store the key 368 err = csp.ks.StoreKey(hmacedKey) 369 if err != nil { 370 return nil, fmt.Errorf("Failed storing ECDSA key [%s]", err) 371 } 372 } 373 374 return hmacedKey, nil 375 376 case *bccsp.HMACDeriveKeyOpts: 377 378 hmacOpts := opts.(*bccsp.HMACDeriveKeyOpts) 379 380 mac := hmac.New(csp.conf.hashFunction, aesK.privKey) 381 mac.Write(hmacOpts.Argument()) 382 hmacedKey := &aesPrivateKey{mac.Sum(nil), true} 383 384 // If the key is not Ephemeral, store it. 385 if !opts.Ephemeral() { 386 // Store the key 387 err = csp.ks.StoreKey(hmacedKey) 388 if err != nil { 389 return nil, fmt.Errorf("Failed storing ECDSA key [%s]", err) 390 } 391 } 392 393 return hmacedKey, nil 394 395 default: 396 return nil, fmt.Errorf("Unrecognized KeyDerivOpts provided [%s]", opts.Algorithm()) 397 398 } 399 400 default: 401 return nil, fmt.Errorf("Key type not recognized [%s]", k) 402 } 403 } 404 405 // KeyImport imports a key from its raw representation using opts. 406 // The opts argument should be appropriate for the primitive used. 407 func (csp *impl) KeyImport(raw interface{}, opts bccsp.KeyImportOpts) (k bccsp.Key, err error) { 408 // Validate arguments 409 if raw == nil { 410 return nil, errors.New("Invalid raw. Cannot be nil") 411 } 412 413 if opts == nil { 414 return nil, errors.New("Invalid Opts parameter. It must not be nil.") 415 } 416 417 switch opts.(type) { 418 419 case *bccsp.AES256ImportKeyOpts: 420 aesRaw, ok := raw.([]byte) 421 if !ok { 422 return nil, errors.New("[AES256ImportKeyOpts] Invalid raw material. Expected byte array.") 423 } 424 425 if len(aesRaw) != 32 { 426 return nil, fmt.Errorf("[AES256ImportKeyOpts] Invalid Key Length [%d]. Must be 32 bytes", len(aesRaw)) 427 } 428 429 aesK := &aesPrivateKey{utils.Clone(aesRaw), false} 430 431 // If the key is not Ephemeral, store it. 432 if !opts.Ephemeral() { 433 // Store the key 434 err = csp.ks.StoreKey(aesK) 435 if err != nil { 436 return nil, fmt.Errorf("Failed storing AES key [%s]", err) 437 } 438 } 439 440 return aesK, nil 441 442 case *bccsp.HMACImportKeyOpts: 443 aesRaw, ok := raw.([]byte) 444 if !ok { 445 return nil, errors.New("[HMACImportKeyOpts] Invalid raw material. Expected byte array.") 446 } 447 448 if len(aesRaw) == 0 { 449 return nil, errors.New("[HMACImportKeyOpts] Invalid raw. It must not be nil.") 450 } 451 452 aesK := &aesPrivateKey{utils.Clone(aesRaw), false} 453 454 // If the key is not Ephemeral, store it. 455 if !opts.Ephemeral() { 456 // Store the key 457 err = csp.ks.StoreKey(aesK) 458 if err != nil { 459 return nil, fmt.Errorf("Failed storing AES key [%s]", err) 460 } 461 } 462 463 return aesK, nil 464 465 case *bccsp.ECDSAPKIXPublicKeyImportOpts: 466 der, ok := raw.([]byte) 467 if !ok { 468 return nil, errors.New("[ECDSAPKIXPublicKeyImportOpts] Invalid raw material. Expected byte array.") 469 } 470 471 if len(der) == 0 { 472 return nil, errors.New("[ECDSAPKIXPublicKeyImportOpts] Invalid raw. It must not be nil.") 473 } 474 475 lowLevelKey, err := utils.DERToPublicKey(der) 476 if err != nil { 477 return nil, fmt.Errorf("Failed converting PKIX to ECDSA public key [%s]", err) 478 } 479 480 ecdsaPK, ok := lowLevelKey.(*ecdsa.PublicKey) 481 if !ok { 482 return nil, errors.New("Failed casting to ECDSA public key. Invalid raw material.") 483 } 484 485 ecPt := elliptic.Marshal(ecdsaPK.Curve, ecdsaPK.X, ecdsaPK.Y) 486 oid, ok := oidFromNamedCurve(ecdsaPK.Curve) 487 if !ok { 488 return nil, errors.New("Do not know OID for this Curve.") 489 } 490 491 ski, err := importECKey(oid, nil, ecPt, opts.Ephemeral(), isPublicKey) 492 if err != nil { 493 return nil, fmt.Errorf("Failed getting importing EC Public Key [%s]", err) 494 } 495 496 k = &ecdsaPublicKey{ski, ecdsaPK} 497 return k, nil 498 499 case *bccsp.ECDSAPrivateKeyImportOpts: 500 der, ok := raw.([]byte) 501 if !ok { 502 return nil, errors.New("[ECDSADERPrivateKeyImportOpts] Invalid raw material. Expected byte array.") 503 } 504 505 if len(der) == 0 { 506 return nil, errors.New("[ECDSADERPrivateKeyImportOpts] Invalid raw. It must not be nil.") 507 } 508 509 lowLevelKey, err := utils.DERToPrivateKey(der) 510 if err != nil { 511 return nil, fmt.Errorf("Failed converting PKIX to ECDSA public key [%s]", err) 512 } 513 514 ecdsaSK, ok := lowLevelKey.(*ecdsa.PrivateKey) 515 if !ok { 516 return nil, errors.New("Failed casting to ECDSA public key. Invalid raw material.") 517 } 518 519 ecPt := elliptic.Marshal(ecdsaSK.Curve, ecdsaSK.X, ecdsaSK.Y) 520 oid, ok := oidFromNamedCurve(ecdsaSK.Curve) 521 if !ok { 522 return nil, errors.New("Do not know OID for this Curve.") 523 } 524 525 ski, err := importECKey(oid, ecdsaSK.D.Bytes(), ecPt, opts.Ephemeral(), isPrivateKey) 526 if err != nil { 527 return nil, fmt.Errorf("Failed getting importing EC Private Key [%s]", err) 528 } 529 530 k = &ecdsaPrivateKey{ski, ecdsaPublicKey{ski, &ecdsaSK.PublicKey}} 531 return k, nil 532 533 case *bccsp.ECDSAGoPublicKeyImportOpts: 534 lowLevelKey, ok := raw.(*ecdsa.PublicKey) 535 if !ok { 536 return nil, errors.New("[ECDSAGoPublicKeyImportOpts] Invalid raw material. Expected *ecdsa.PublicKey.") 537 } 538 539 ecPt := elliptic.Marshal(lowLevelKey.Curve, lowLevelKey.X, lowLevelKey.Y) 540 oid, ok := oidFromNamedCurve(lowLevelKey.Curve) 541 if !ok { 542 return nil, errors.New("Do not know OID for this Curve.") 543 } 544 545 ski, err := importECKey(oid, nil, ecPt, opts.Ephemeral(), isPublicKey) 546 if err != nil { 547 return nil, fmt.Errorf("Failed getting importing EC Public Key [%s]", err) 548 } 549 550 k = &ecdsaPublicKey{ski, lowLevelKey} 551 return k, nil 552 553 case *bccsp.RSAGoPublicKeyImportOpts: 554 lowLevelKey, ok := raw.(*rsa.PublicKey) 555 if !ok { 556 return nil, errors.New("[RSAGoPublicKeyImportOpts] Invalid raw material. Expected *rsa.PublicKey.") 557 } 558 559 k = &rsaPublicKey{lowLevelKey} 560 561 // If the key is not Ephemeral, store it. 562 if !opts.Ephemeral() { 563 // Store the key 564 err = csp.ks.StoreKey(k) 565 if err != nil { 566 return nil, fmt.Errorf("Failed storing RSA publi key [%s]", err) 567 } 568 } 569 570 return k, nil 571 572 case *bccsp.X509PublicKeyImportOpts: 573 x509Cert, ok := raw.(*x509.Certificate) 574 if !ok { 575 return nil, errors.New("[X509PublicKeyImportOpts] Invalid raw material. Expected *x509.Certificate.") 576 } 577 578 pk := x509Cert.PublicKey 579 580 switch pk.(type) { 581 case *ecdsa.PublicKey: 582 return csp.KeyImport(pk, &bccsp.ECDSAGoPublicKeyImportOpts{Temporary: opts.Ephemeral()}) 583 case *rsa.PublicKey: 584 return csp.KeyImport(pk, &bccsp.RSAGoPublicKeyImportOpts{Temporary: opts.Ephemeral()}) 585 default: 586 return nil, errors.New("Certificate public key type not recognized. Supported keys: [ECDSA, RSA]") 587 } 588 589 default: 590 return nil, errors.New("Import Key Options not recognized") 591 } 592 } 593 594 // GetKey returns the key this CSP associates to 595 // the Subject Key Identifier ski. 596 func (csp *impl) GetKey(ski []byte) (k bccsp.Key, err error) { 597 pubKey, isPriv, err := getECKey(ski) 598 if err == nil { 599 if isPriv { 600 return &ecdsaPrivateKey{ski, ecdsaPublicKey{ski, pubKey}}, nil 601 } else { 602 return &ecdsaPublicKey{ski, pubKey}, nil 603 } 604 } 605 return csp.ks.GetKey(ski) 606 } 607 608 // Hash hashes messages msg using options opts. 609 func (csp *impl) Hash(msg []byte, opts bccsp.HashOpts) (digest []byte, err error) { 610 var h hash.Hash 611 if opts == nil { 612 h = csp.conf.hashFunction() 613 } else { 614 switch opts.(type) { 615 case *bccsp.SHAOpts: 616 h = csp.conf.hashFunction() 617 case *bccsp.SHA256Opts: 618 h = sha256.New() 619 case *bccsp.SHA384Opts: 620 h = sha512.New384() 621 case *bccsp.SHA3_256Opts: 622 h = sha3.New256() 623 case *bccsp.SHA3_384Opts: 624 h = sha3.New384() 625 default: 626 return nil, fmt.Errorf("Algorithm not recognized [%s]", opts.Algorithm()) 627 } 628 } 629 630 h.Write(msg) 631 return h.Sum(nil), nil 632 } 633 634 // GetHash returns and instance of hash.Hash using options opts. 635 // If opts is nil then the default hash function is returned. 636 func (csp *impl) GetHash(opts bccsp.HashOpts) (h hash.Hash, err error) { 637 if opts == nil { 638 return csp.conf.hashFunction(), nil 639 } 640 641 switch opts.(type) { 642 case *bccsp.SHAOpts: 643 return csp.conf.hashFunction(), nil 644 case *bccsp.SHA256Opts: 645 return sha256.New(), nil 646 case *bccsp.SHA384Opts: 647 return sha512.New384(), nil 648 case *bccsp.SHA3_256Opts: 649 return sha3.New256(), nil 650 case *bccsp.SHA3_384Opts: 651 return sha3.New384(), nil 652 default: 653 return nil, fmt.Errorf("Algorithm not recognized [%s]", opts.Algorithm()) 654 } 655 } 656 657 // Sign signs digest using key k. 658 // The opts argument should be appropriate for the primitive used. 659 // 660 // Note that when a signature of a hash of a larger message is needed, 661 // the caller is responsible for hashing the larger message and passing 662 // the hash (as digest). 663 func (csp *impl) Sign(k bccsp.Key, digest []byte, opts bccsp.SignerOpts) (signature []byte, err error) { 664 // Validate arguments 665 if k == nil { 666 return nil, errors.New("Invalid Key. It must not be nil.") 667 } 668 if len(digest) == 0 { 669 return nil, errors.New("Invalid digest. Cannot be empty.") 670 } 671 672 // Check key type 673 switch k.(type) { 674 case *ecdsaPrivateKey: 675 return csp.signECDSA(*k.(*ecdsaPrivateKey), digest, opts) 676 case *rsaPrivateKey: 677 if opts == nil { 678 return nil, errors.New("Invalid options. Nil.") 679 } 680 681 return k.(*rsaPrivateKey).privKey.Sign(rand.Reader, digest, opts) 682 default: 683 return nil, fmt.Errorf("Key type not recognized [%s]", k) 684 } 685 } 686 687 // Verify verifies signature against key k and digest 688 func (csp *impl) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (valid bool, err error) { 689 // Validate arguments 690 if k == nil { 691 return false, errors.New("Invalid Key. It must not be nil.") 692 } 693 if len(signature) == 0 { 694 return false, errors.New("Invalid signature. Cannot be empty.") 695 } 696 if len(digest) == 0 { 697 return false, errors.New("Invalid digest. Cannot be empty.") 698 } 699 700 // Check key type 701 switch k.(type) { 702 case *ecdsaPrivateKey: 703 return csp.verifyECDSA(k.(*ecdsaPrivateKey).pub, signature, digest, opts) 704 case *ecdsaPublicKey: 705 return csp.verifyECDSA(*k.(*ecdsaPublicKey), signature, digest, opts) 706 case *rsaPrivateKey: 707 if opts == nil { 708 return false, errors.New("Invalid options. It must not be nil.") 709 } 710 switch opts.(type) { 711 case *rsa.PSSOptions: 712 err := rsa.VerifyPSS(&(k.(*rsaPrivateKey).privKey.PublicKey), 713 (opts.(*rsa.PSSOptions)).Hash, 714 digest, signature, opts.(*rsa.PSSOptions)) 715 716 return err == nil, err 717 default: 718 return false, fmt.Errorf("Opts type not recognized [%s]", opts) 719 } 720 case *rsaPublicKey: 721 if opts == nil { 722 return false, errors.New("Invalid options. It must not be nil.") 723 } 724 switch opts.(type) { 725 case *rsa.PSSOptions: 726 err := rsa.VerifyPSS(k.(*rsaPublicKey).pubKey, 727 (opts.(*rsa.PSSOptions)).Hash, 728 digest, signature, opts.(*rsa.PSSOptions)) 729 730 return err == nil, err 731 default: 732 return false, fmt.Errorf("Opts type not recognized [%s]", opts) 733 } 734 default: 735 return false, fmt.Errorf("Key type not recognized [%s]", k) 736 } 737 } 738 739 // Encrypt encrypts plaintext using key k. 740 // The opts argument should be appropriate for the primitive used. 741 func (csp *impl) Encrypt(k bccsp.Key, plaintext []byte, opts bccsp.EncrypterOpts) (ciphertext []byte, err error) { 742 // Validate arguments 743 if k == nil { 744 return nil, errors.New("Invalid Key. It must not be nil.") 745 } 746 747 // Check key type 748 switch k.(type) { 749 case *aesPrivateKey: 750 // check for mode 751 switch opts.(type) { 752 case *bccsp.AESCBCPKCS7ModeOpts, bccsp.AESCBCPKCS7ModeOpts: 753 // AES in CBC mode with PKCS7 padding 754 return AESCBCPKCS7Encrypt(k.(*aesPrivateKey).privKey, plaintext) 755 default: 756 return nil, fmt.Errorf("Mode not recognized [%s]", opts) 757 } 758 default: 759 return nil, fmt.Errorf("Key type not recognized [%s]", k) 760 } 761 } 762 763 // Decrypt decrypts ciphertext using key k. 764 // The opts argument should be appropriate for the primitive used. 765 func (csp *impl) Decrypt(k bccsp.Key, ciphertext []byte, opts bccsp.DecrypterOpts) (plaintext []byte, err error) { 766 // Validate arguments 767 if k == nil { 768 return nil, errors.New("Invalid Key. It must not be nil.") 769 } 770 771 // Check key type 772 switch k.(type) { 773 case *aesPrivateKey: 774 // check for mode 775 switch opts.(type) { 776 case *bccsp.AESCBCPKCS7ModeOpts, bccsp.AESCBCPKCS7ModeOpts: 777 // AES in CBC mode with PKCS7 padding 778 return AESCBCPKCS7Decrypt(k.(*aesPrivateKey).privKey, ciphertext) 779 default: 780 return nil, fmt.Errorf("Mode not recognized [%s]", opts) 781 } 782 default: 783 return nil, fmt.Errorf("Key type not recognized [%s]", k) 784 } 785 }