diff --git a/core/crypto/bccsp/sw/aes_test.go b/core/crypto/bccsp/sw/aes_test.go new file mode 100644 index 00000000000..3123ae23c92 --- /dev/null +++ b/core/crypto/bccsp/sw/aes_test.go @@ -0,0 +1,478 @@ +/* +Copyright IBM Corp. 2016 All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package sw + +import ( + "bytes" + "crypto/aes" + "crypto/rand" + "math/big" + "testing" + + "github.com/hyperledger/fabric/core/crypto/bccsp/utils" +) + +// TestCBCPKCS7EncryptCBCPKCS7Decrypt encrypts using CBCPKCS7Encrypt and decrypts using CBCPKCS7Decrypt. +func TestCBCPKCS7EncryptCBCPKCS7Decrypt(t *testing.T) { + + // Note: The purpose of this test is not to test AES-256 in CBC mode's strength + // ... but rather to verify the code wrapping/unwrapping the cipher. + key := make([]byte, 32) + rand.Reader.Read(key) + + // 123456789012345678901234567890123456789012 + var ptext = []byte("a message with arbitrary length (42 bytes)") + + encrypted, encErr := AESCBCPKCS7Encrypt(key, ptext) + if encErr != nil { + t.Fatalf("Error encrypting '%s': %s", ptext, encErr) + } + + decrypted, dErr := AESCBCPKCS7Decrypt(key, encrypted) + if dErr != nil { + t.Fatalf("Error decrypting the encrypted '%s': %v", ptext, dErr) + } + + if string(ptext[:]) != string(decrypted[:]) { + t.Fatal("Decrypt( Encrypt( ptext ) ) != ptext: Ciphertext decryption with the same key must result in the original plaintext!") + } + +} + +// TestPKCS7Padding verifies the PKCS#7 padding, using a human readable plaintext. +func TestPKCS7Padding(t *testing.T) { + + // 0 byte/length ptext + ptext := []byte("") + expected := []byte{16, 16, 16, 16, + 16, 16, 16, 16, + 16, 16, 16, 16, + 16, 16, 16, 16} + result := pkcs7Padding(ptext) + + if !bytes.Equal(expected, result) { + t.Fatal("Padding error! Expected: ", expected, "', received: '", result, "'") + } + + // 1 byte/length ptext + ptext = []byte("1") + expected = []byte{'1', 15, 15, 15, + 15, 15, 15, 15, + 15, 15, 15, 15, + 15, 15, 15, 15} + result = pkcs7Padding(ptext) + + if !bytes.Equal(expected, result) { + t.Fatal("Padding error! Expected: '", expected, "', received: '", result, "'") + } + + // 2 byte/length ptext + ptext = []byte("12") + expected = []byte{'1', '2', 14, 14, + 14, 14, 14, 14, + 14, 14, 14, 14, + 14, 14, 14, 14} + result = pkcs7Padding(ptext) + + if !bytes.Equal(expected, result) { + t.Fatal("Padding error! Expected: '", expected, "', received: '", result, "'") + } + + // 3 to aes.BlockSize-1 byte plaintext + ptext = []byte("1234567890ABCDEF") + for i := 3; i < aes.BlockSize; i++ { + result := pkcs7Padding(ptext[:i]) + + padding := aes.BlockSize - i + expectedPadding := bytes.Repeat([]byte{byte(padding)}, padding) + expected = append(ptext[:i], expectedPadding...) + + if !bytes.Equal(result, expected) { + t.Fatal("Padding error! Expected: '", expected, "', received: '", result, "'") + } + + } + + // aes.BlockSize length ptext + ptext = bytes.Repeat([]byte{byte('x')}, aes.BlockSize) + result = pkcs7Padding(ptext) + + expectedPadding := bytes.Repeat([]byte{byte(aes.BlockSize)}, aes.BlockSize) + expected = append(ptext, expectedPadding...) + + if len(result) != 2*aes.BlockSize { + t.Fatal("Padding error: expected the length of the returned slice to be 2 times aes.BlockSize") + } + + if !bytes.Equal(expected, result) { + t.Fatal("Padding error! Expected: '", expected, "', received: '", result, "'") + } + +} + +// TestPKCS7UnPadding verifies the PKCS#7 unpadding, using a human readable plaintext. +func TestPKCS7UnPadding(t *testing.T) { + + // 0 byte/length ptext + expected := []byte("") + ptext := []byte{16, 16, 16, 16, + 16, 16, 16, 16, + 16, 16, 16, 16, + 16, 16, 16, 16} + + result, _ := pkcs7UnPadding(ptext) + + if !bytes.Equal(expected, result) { + t.Fatal("UnPadding error! Expected: '", expected, "', received: '", result, "'") + } + + // 1 byte/length ptext + expected = []byte("1") + ptext = []byte{'1', 15, 15, 15, + 15, 15, 15, 15, + 15, 15, 15, 15, + 15, 15, 15, 15} + + result, _ = pkcs7UnPadding(ptext) + + if !bytes.Equal(expected, result) { + t.Fatal("UnPadding error! Expected: '", expected, "', received: '", result, "'") + } + + // 2 byte/length ptext + expected = []byte("12") + ptext = []byte{'1', '2', 14, 14, + 14, 14, 14, 14, + 14, 14, 14, 14, + 14, 14, 14, 14} + + result, _ = pkcs7UnPadding(ptext) + + if !bytes.Equal(expected, result) { + t.Fatal("UnPadding error! Expected: '", expected, "', received: '", result, "'") + } + + // 3 to aes.BlockSize-1 byte plaintext + base := []byte("1234567890ABCDEF") + for i := 3; i < aes.BlockSize; i++ { + iPad := aes.BlockSize - i + padding := bytes.Repeat([]byte{byte(iPad)}, iPad) + ptext = append(base[:i], padding...) + + expected := base[:i] + result, _ := pkcs7UnPadding(ptext) + + if !bytes.Equal(result, expected) { + t.Fatal("UnPadding error! Expected: '", expected, "', received: '", result, "'") + } + + } + + // aes.BlockSize length ptext + expected = bytes.Repeat([]byte{byte('x')}, aes.BlockSize) + padding := bytes.Repeat([]byte{byte(aes.BlockSize)}, aes.BlockSize) + ptext = append(expected, padding...) + + result, _ = pkcs7UnPadding(ptext) + + if !bytes.Equal(expected, result) { + t.Fatal("UnPadding error! Expected: '", expected, "', received: '", result, "'") + } +} + +// TestCBCEncryptCBCPKCS7Decrypt_BlockSizeLengthPlaintext verifies that CBCPKCS7Decrypt returns an error +// when attempting to decrypt ciphertext of an irreproducible length. +func TestCBCEncryptCBCPKCS7Decrypt_BlockSizeLengthPlaintext(t *testing.T) { + + // One of the purposes of this test is to also document and clarify the expected behavior, i.e., that an extra + // block is appended to the message at the padding stage, as per the spec of PKCS#7 v1.5 [see RFC-2315 p.21] + key := make([]byte, 32) + rand.Reader.Read(key) + + // 1234567890123456 + var ptext = []byte("a 16 byte messag") + + encrypted, encErr := aesCBCEncrypt(key, ptext) + if encErr != nil { + t.Fatalf("Error encrypting '%s': %v", ptext, encErr) + } + + decrypted, dErr := AESCBCPKCS7Decrypt(key, encrypted) + if dErr == nil { + t.Fatalf("Expected an error decrypting ptext '%s'. Decrypted to '%v'", dErr, decrypted) + } +} + +// TestCBCPKCS7EncryptCBCDecrypt_ExpectingCorruptMessage verifies that CBCDecrypt can decrypt the unpadded +// version of the ciphertext, of a message of BlockSize length. +func TestCBCPKCS7EncryptCBCDecrypt_ExpectingCorruptMessage(t *testing.T) { + + // One of the purposes of this test is to also document and clarify the expected behavior, i.e., that an extra + // block is appended to the message at the padding stage, as per the spec of PKCS#7 v1.5 [see RFC-2315 p.21] + key := make([]byte, 32) + rand.Reader.Read(key) + + // 0123456789ABCDEF + var ptext = []byte("a 16 byte messag") + + encrypted, encErr := AESCBCPKCS7Encrypt(key, ptext) + if encErr != nil { + t.Fatalf("Error encrypting ptext %v", encErr) + } + + decrypted, dErr := aesCBCDecrypt(key, encrypted) + if dErr != nil { + t.Fatalf("Error encrypting ptext %v, %v", dErr, decrypted) + } + + if string(ptext[:]) != string(decrypted[:aes.BlockSize]) { + t.Log("ptext: ", ptext) + t.Log("decrypted: ", decrypted[:aes.BlockSize]) + t.Fatal("Encryption->Decryption with same key should result in original ptext") + } + + if !bytes.Equal(decrypted[aes.BlockSize:], bytes.Repeat([]byte{byte(aes.BlockSize)}, aes.BlockSize)) { + t.Fatal("Expected extra block with padding in encrypted ptext", decrypted) + } + +} + +// TestCBCPKCS7Encrypt_EmptyPlaintext encrypts and pad an empty ptext. Verifying as well that the ciphertext length is as expected. +func TestCBCPKCS7Encrypt_EmptyPlaintext(t *testing.T) { + + key := make([]byte, 32) + rand.Reader.Read(key) + + t.Log("Generated key: ", key) + + var emptyPlaintext = []byte("") + t.Log("Plaintext length: ", len(emptyPlaintext)) + + ciphertext, encErr := AESCBCPKCS7Encrypt(key, emptyPlaintext) + if encErr != nil { + t.Fatalf("Error encrypting '%v'", encErr) + } + + // Expected ciphertext length: 32 (=32) + // As part of the padding, at least one block gets encrypted (while the first block is the IV) + const expectedLength = aes.BlockSize + aes.BlockSize + if len(ciphertext) != expectedLength { + t.Fatalf("Wrong ciphertext length. Expected %d, recieved %d", expectedLength, len(ciphertext)) + } + + t.Log("Ciphertext length: ", len(ciphertext)) + t.Log("Cipher: ", ciphertext) +} + +// TestCBCEncrypt_EmptyPlaintext encrypts an empty message. Verifying as well that the ciphertext length is as expected. +func TestCBCEncrypt_EmptyPlaintext(t *testing.T) { + + key := make([]byte, 32) + rand.Reader.Read(key) + t.Log("Generated key: ", key) + + var emptyPlaintext = []byte("") + t.Log("Message length: ", len(emptyPlaintext)) + + ciphertext, encErr := aesCBCEncrypt(key, emptyPlaintext) + if encErr != nil { + } + + t.Log("Ciphertext length: ", len(ciphertext)) + + // Expected cipher length: aes.BlockSize, the first and only block is the IV + var expectedLength = aes.BlockSize + + if len(ciphertext) != expectedLength { + t.Fatalf("Wrong ciphertext length. Expected: '%d', received: '%d'", expectedLength, len(ciphertext)) + } + t.Log("Ciphertext: ", ciphertext) +} + +// TestCBCPKCS7Encrypt_VerifyRandomIVs encrypts twice with same key. The first 16 bytes should be different if IV is generated randomly. +func TestCBCPKCS7Encrypt_VerifyRandomIVs(t *testing.T) { + + key := make([]byte, aes.BlockSize) + rand.Reader.Read(key) + t.Log("Key 1", key) + + var ptext = []byte("a message to encrypt") + + ciphertext1, err := AESCBCPKCS7Encrypt(key, ptext) + if err != nil { + t.Fatalf("Error encrypting '%s': %s", ptext, err) + } + + // Expecting a different IV if same message is encrypted with same key + ciphertext2, err := AESCBCPKCS7Encrypt(key, ptext) + if err != nil { + t.Fatalf("Error encrypting '%s': %s", ptext, err) + } + + iv1 := ciphertext1[:aes.BlockSize] + iv2 := ciphertext2[:aes.BlockSize] + + t.Log("Ciphertext1: ", iv1) + t.Log("Ciphertext2: ", iv2) + t.Log("bytes.Equal: ", bytes.Equal(iv1, iv2)) + + if bytes.Equal(iv1, iv2) { + t.Fatal("Error: ciphertexts contain identical initialization vectors (IVs)") + } +} + +// TestCBCPKCS7Encrypt_CorrectCiphertextLengthCheck verifies that the returned ciphertext lengths are as expected. +func TestCBCPKCS7Encrypt_CorrectCiphertextLengthCheck(t *testing.T) { + + key := make([]byte, aes.BlockSize) + rand.Reader.Read(key) + + // length of message (in bytes) == aes.BlockSize (16 bytes) + // The expected cipher length = IV length (1 block) + 1 block message + + var ptext = []byte("0123456789ABCDEF") + + for i := 1; i < aes.BlockSize; i++ { + ciphertext, err := AESCBCPKCS7Encrypt(key, ptext[:i]) + if err != nil { + t.Fatal("Error encrypting '", ptext, "'") + } + + expectedLength := aes.BlockSize + aes.BlockSize + if len(ciphertext) != expectedLength { + t.Fatalf("Incorrect ciphertext incorrect: expected '%d', received '%d'", expectedLength, len(ciphertext)) + } + } +} + +// TestCBCEncryptCBCDecrypt_KeyMismatch attempts to decrypt with a different key than the one used for encryption. +func TestCBCEncryptCBCDecrypt_KeyMismatch(t *testing.T) { + + // Generate a random key + key := make([]byte, aes.BlockSize) + rand.Reader.Read(key) + + // Clone & tamper with the key + wrongKey := make([]byte, aes.BlockSize) + copy(wrongKey, key[:]) + wrongKey[0] = key[0] + 1 + + var ptext = []byte("1234567890ABCDEF") + encrypted, encErr := aesCBCEncrypt(key, ptext) + if encErr != nil { + t.Fatalf("Error encrypting '%s': %v", ptext, encErr) + } + + decrypted, decErr := aesCBCDecrypt(wrongKey, encrypted) + if decErr != nil { + t.Fatalf("Error decrypting '%s': %v", ptext, decErr) + } + + if string(ptext[:]) == string(decrypted[:]) { + t.Fatal("Decrypting a ciphertext with a different key than the one used for encrypting it - should not result in the original plaintext.") + } +} + +// TestCBCEncryptCBCDecrypt encrypts with CBCEncrypt and decrypt with CBCDecrypt. +func TestCBCEncryptCBCDecrypt(t *testing.T) { + + key := make([]byte, 32) + rand.Reader.Read(key) + + // 1234567890123456 + var ptext = []byte("a 16 byte messag") + + encrypted, encErr := aesCBCEncrypt(key, ptext) + if encErr != nil { + t.Fatalf("Error encrypting '%s': %v", ptext, encErr) + } + + decrypted, decErr := aesCBCDecrypt(key, encrypted) + if decErr != nil { + t.Fatalf("Error decrypting '%s': %v", ptext, decErr) + } + + if string(ptext[:]) != string(decrypted[:]) { + t.Fatal("Encryption->Decryption with same key should result in the original plaintext.") + } +} + +// TestAESRelatedUtilFunctions tests various functions commonly used in fabric wrt AES +func TestAESRelatedUtilFunctions(t *testing.T) { + + key, err := GetRandomBytes(32) + if err != nil { + t.Fatalf("Failed generating AES key [%s]", err) + } + + for i := 1; i < 100; i++ { + l, err := rand.Int(rand.Reader, big.NewInt(1024)) + if err != nil { + t.Fatalf("Failed generating AES key [%s]", err) + } + msg, err := GetRandomBytes(int(l.Int64()) + 1) + if err != nil { + t.Fatalf("Failed generating AES key [%s]", err) + } + + ct, err := AESCBCPKCS7Encrypt(key, msg) + if err != nil { + t.Fatalf("Failed encrypting [%s]", err) + } + + msg2, err := AESCBCPKCS7Decrypt(key, ct) + if err != nil { + t.Fatalf("Failed decrypting [%s]", err) + } + + if 0 != bytes.Compare(msg, msg2) { + t.Fatalf("Wrong decryption output [%x][%x]", msg, msg2) + } + + } + +} + +// TestVariousAESKeyEncoding tests some AES <-> PEM conversions +func TestVariousAESKeyEncoding(t *testing.T) { + key, err := GetRandomBytes(32) + if err != nil { + t.Fatalf("Failed generating AES key [%s]", err) + } + + // PEM format + pem := utils.AEStoPEM(key) + keyFromPEM, err := utils.PEMtoAES(pem, nil) + if err != nil { + t.Fatalf("Failed converting PEM to AES key [%s]", err) + } + if 0 != bytes.Compare(key, keyFromPEM) { + t.Fatalf("Failed converting PEM to AES key. Keys are different [%x][%x]", key, keyFromPEM) + } + + // Encrypted PEM format + pem, err = utils.AEStoEncryptedPEM(key, []byte("passwd")) + if err != nil { + t.Fatalf("Failed converting AES key to Encrypted PEM [%s]", err) + } + keyFromPEM, err = utils.PEMtoAES(pem, []byte("passwd")) + if err != nil { + t.Fatalf("Failed converting encrypted PEM to AES key [%s]", err) + } + if 0 != bytes.Compare(key, keyFromPEM) { + t.Fatalf("Failed converting encrypted PEM to AES key. Keys are different [%x][%x]", key, keyFromPEM) + } +} diff --git a/core/crypto/bccsp/utils/keys_test.go b/core/crypto/bccsp/utils/keys_test.go new file mode 100644 index 00000000000..49c4b9651ec --- /dev/null +++ b/core/crypto/bccsp/utils/keys_test.go @@ -0,0 +1,186 @@ +package utils + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "testing" +) + +func TestECDSAKeys(t *testing.T) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatalf("Failed generating ECDSA key [%s]", err) + } + + // Private Key DER format + der, err := PrivateKeyToDER(key) + if err != nil { + t.Fatalf("Failed converting private key to DER [%s]", err) + } + keyFromDER, err := DERToPrivateKey(der) + if err != nil { + t.Fatalf("Failed converting DER to private key [%s]", err) + } + ecdsaKeyFromDer := keyFromDER.(*ecdsa.PrivateKey) + // TODO: check the curve + if key.D.Cmp(ecdsaKeyFromDer.D) != 0 { + t.Fatal("Failed converting DER to private key. Invalid D.") + } + if key.X.Cmp(ecdsaKeyFromDer.X) != 0 { + t.Fatal("Failed converting DER to private key. Invalid X coordinate.") + } + if key.Y.Cmp(ecdsaKeyFromDer.Y) != 0 { + t.Fatal("Failed converting DER to private key. Invalid Y coordinate.") + } + + // Private Key PEM format + pem, err := PrivateKeyToPEM(key, nil) + if err != nil { + t.Fatalf("Failed converting private key to PEM [%s]", err) + } + keyFromPEM, err := PEMtoPrivateKey(pem, nil) + if err != nil { + t.Fatalf("Failed converting DER to private key [%s]", err) + } + ecdsaKeyFromPEM := keyFromPEM.(*ecdsa.PrivateKey) + // TODO: check the curve + if key.D.Cmp(ecdsaKeyFromPEM.D) != 0 { + t.Fatal("Failed converting PEM to private key. Invalid D.") + } + if key.X.Cmp(ecdsaKeyFromPEM.X) != 0 { + t.Fatal("Failed converting PEM to private key. Invalid X coordinate.") + } + if key.Y.Cmp(ecdsaKeyFromPEM.Y) != 0 { + t.Fatal("Failed converting PEM to private key. Invalid Y coordinate.") + } + + // Nil Private Key <-> PEM + _, err = PrivateKeyToPEM(nil, nil) + if err == nil { + t.Fatal("PublicKeyToPEM should fail on nil") + } + + _, err = PEMtoPrivateKey(nil, nil) + if err == nil { + t.Fatal("PEMtoPublicKey should fail on nil") + } + + _, err = PEMtoPrivateKey([]byte{0, 1, 3, 4}, nil) + if err == nil { + t.Fatal("PEMtoPublicKey should fail invalid PEM") + } + + _, err = DERToPrivateKey(nil) + if err == nil { + t.Fatal("DERToPrivateKey should fail on nil") + } + + _, err = DERToPrivateKey([]byte{0, 1, 3, 4}) + if err == nil { + t.Fatal("DERToPrivateKey should fail on invalid DER") + } + + _, err = PrivateKeyToDER(nil) + if err == nil { + t.Fatal("DERToPrivateKey should fail on nil") + } + + // Private Key Encrypted PEM format + encPEM, err := PrivateKeyToPEM(key, []byte("passwd")) + if err != nil { + t.Fatalf("Failed converting private key to encrypted PEM [%s]", err) + } + encKeyFromPEM, err := PEMtoPrivateKey(encPEM, []byte("passwd")) + if err != nil { + t.Fatalf("Failed converting DER to private key [%s]", err) + } + ecdsaKeyFromEncPEM := encKeyFromPEM.(*ecdsa.PrivateKey) + // TODO: check the curve + if key.D.Cmp(ecdsaKeyFromEncPEM.D) != 0 { + t.Fatal("Failed converting encrypted PEM to private key. Invalid D.") + } + if key.X.Cmp(ecdsaKeyFromEncPEM.X) != 0 { + t.Fatal("Failed converting encrypted PEM to private key. Invalid X coordinate.") + } + if key.Y.Cmp(ecdsaKeyFromEncPEM.Y) != 0 { + t.Fatal("Failed converting encrypted PEM to private key. Invalid Y coordinate.") + } + + // Public Key PEM format + pem, err = PublicKeyToPEM(&key.PublicKey, nil) + if err != nil { + t.Fatalf("Failed converting public key to PEM [%s]", err) + } + keyFromPEM, err = PEMtoPublicKey(pem, nil) + if err != nil { + t.Fatalf("Failed converting DER to public key [%s]", err) + } + ecdsaPkFromPEM := keyFromPEM.(*ecdsa.PublicKey) + // TODO: check the curve + if key.X.Cmp(ecdsaPkFromPEM.X) != 0 { + t.Fatal("Failed converting PEM to private key. Invalid X coordinate.") + } + if key.Y.Cmp(ecdsaPkFromPEM.Y) != 0 { + t.Fatal("Failed converting PEM to private key. Invalid Y coordinate.") + } + + // Nil Public Key <-> PEM + _, err = PublicKeyToPEM(nil, nil) + if err == nil { + t.Fatal("PublicKeyToPEM should fail on nil") + } + + _, err = PEMtoPublicKey(nil, nil) + if err == nil { + t.Fatal("PEMtoPublicKey should fail on nil") + } + + _, err = PEMtoPublicKey([]byte{0, 1, 3, 4}, nil) + if err == nil { + t.Fatal("PEMtoPublicKey should fail on invalid PEM") + } + + // Public Key Encrypted PEM format + encPEM, err = PublicKeyToPEM(&key.PublicKey, []byte("passwd")) + if err != nil { + t.Fatalf("Failed converting private key to encrypted PEM [%s]", err) + } + pkFromEncPEM, err := PEMtoPublicKey(encPEM, []byte("passwd")) + if err != nil { + t.Fatalf("Failed converting DER to private key [%s]", err) + } + ecdsaPkFromEncPEM := pkFromEncPEM.(*ecdsa.PublicKey) + // TODO: check the curve + if key.X.Cmp(ecdsaPkFromEncPEM.X) != 0 { + t.Fatal("Failed converting encrypted PEM to private key. Invalid X coordinate.") + } + if key.Y.Cmp(ecdsaPkFromEncPEM.Y) != 0 { + t.Fatal("Failed converting encrypted PEM to private key. Invalid Y coordinate.") + } + + _, err = PEMtoPublicKey(encPEM, []byte("passw")) + if err == nil { + t.Fatal("PEMtoPublicKey should fail on wrong password") + } + + _, err = PEMtoPublicKey(encPEM, []byte("passw")) + if err == nil { + t.Fatal("PEMtoPublicKey should fail on nil password") + } + + _, err = PEMtoPublicKey(nil, []byte("passwd")) + if err == nil { + t.Fatal("PEMtoPublicKey should fail on nil PEM") + } + + _, err = PEMtoPublicKey([]byte{0, 1, 3, 4}, []byte("passwd")) + if err == nil { + t.Fatal("PEMtoPublicKey should fail on invalid PEM") + } + + _, err = PEMtoPublicKey(nil, []byte("passw")) + if err == nil { + t.Fatal("PEMtoPublicKey should fail on nil PEM and wrong password") + } +} diff --git a/core/crypto/primitives/crypto.go b/core/crypto/primitives/crypto.go deleted file mode 100644 index adb33685415..00000000000 --- a/core/crypto/primitives/crypto.go +++ /dev/null @@ -1,188 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package primitives - -import ( - "errors" - "io" -) - -var ( - // ErrEncryption Error during encryption - ErrEncryption = errors.New("Error during encryption.") - - // ErrDecryption Error during decryption - ErrDecryption = errors.New("Error during decryption.") - - // ErrInvalidSecretKeyType Invalid Secret Key type - ErrInvalidSecretKeyType = errors.New("Invalid Secret Key type.") - - // ErrInvalidPublicKeyType Invalid Public Key type - ErrInvalidPublicKeyType = errors.New("Invalid Public Key type.") - - // ErrInvalidKeyParameter Invalid Key Parameter - ErrInvalidKeyParameter = errors.New("Invalid Key Parameter.") - - // ErrInvalidNilKeyParameter Invalid Nil Key Parameter - ErrInvalidNilKeyParameter = errors.New("Invalid Nil Key Parameter.") - - // ErrInvalidKeyGeneratorParameter Invalid Key Generator Parameter - ErrInvalidKeyGeneratorParameter = errors.New("Invalid Key Generator Parameter.") -) - -// Parameters is common interface for all the parameters -type Parameters interface { - - // GetRand returns the random generated associated to this parameters - GetRand() io.Reader -} - -// CipherParameters is common interface to represent cipher parameters -type CipherParameters interface { - Parameters -} - -// AsymmetricCipherParameters is common interface to represent asymmetric cipher parameters -type AsymmetricCipherParameters interface { - CipherParameters - - // IsPublic returns true if the parameters are public, false otherwise. - IsPublic() bool -} - -// PublicKey is common interface to represent public asymmetric cipher parameters -type PublicKey interface { - AsymmetricCipherParameters -} - -// PrivateKey is common interface to represent private asymmetric cipher parameters -type PrivateKey interface { - AsymmetricCipherParameters - - // GetPublicKey returns the associated public key - GetPublicKey() PublicKey -} - -// KeyGeneratorParameters is common interface to represent key generation parameters -type KeyGeneratorParameters interface { - Parameters -} - -// KeyGenerator defines a key generator -type KeyGenerator interface { - // Init initializes this generated using the passed parameters - Init(params KeyGeneratorParameters) error - - // GenerateKey generates a new private key - GenerateKey() (PrivateKey, error) -} - -// AsymmetricCipher defines an asymmetric cipher -type AsymmetricCipher interface { - // Init initializes this cipher with the passed parameters - Init(params AsymmetricCipherParameters) error - - // Process processes the byte array given in input - Process(msg []byte) ([]byte, error) -} - -// SecretKey defines a symmetric key -type SecretKey interface { - CipherParameters -} - -// StreamCipher defines a stream cipher -type StreamCipher interface { - // Init initializes this cipher with the passed parameters - Init(forEncryption bool, params CipherParameters) error - - // Process processes the byte array given in input - Process(msg []byte) ([]byte, error) -} - -// KeySerializer defines a key serializer/deserializer -type KeySerializer interface { - // ToBytes converts a key to bytes - ToBytes(key interface{}) ([]byte, error) - - // ToBytes converts bytes to a key - FromBytes([]byte) (interface{}, error) -} - -// AsymmetricCipherSPI is a Service Provider Interface for AsymmetricCipher -type AsymmetricCipherSPI interface { - - // NewAsymmetricCipherFromPrivateKey creates a new AsymmetricCipher for decryption from a secret key - NewAsymmetricCipherFromPrivateKey(priv PrivateKey) (AsymmetricCipher, error) - - // NewAsymmetricCipherFromPublicKey creates a new AsymmetricCipher for encryption from a public key - NewAsymmetricCipherFromPublicKey(pub PublicKey) (AsymmetricCipher, error) - - // NewAsymmetricCipherFromPublicKey creates a new AsymmetricCipher for encryption from a serialized public key - NewAsymmetricCipherFromSerializedPublicKey(pub []byte) (AsymmetricCipher, error) - - // NewAsymmetricCipherFromPublicKey creates a new AsymmetricCipher for encryption from a serialized public key - NewAsymmetricCipherFromSerializedPrivateKey(priv []byte) (AsymmetricCipher, error) - - // NewPrivateKey creates a new private key rand and default parameters - NewDefaultPrivateKey(rand io.Reader) (PrivateKey, error) - - // NewPrivateKey creates a new private key from (rand, params) - NewPrivateKey(rand io.Reader, params interface{}) (PrivateKey, error) - - // NewPublicKey creates a new public key from (rand, params) - NewPublicKey(rand io.Reader, params interface{}) (PublicKey, error) - - // SerializePrivateKey serializes a private key - SerializePrivateKey(priv PrivateKey) ([]byte, error) - - // DeserializePrivateKey deserializes to a private key - DeserializePrivateKey(bytes []byte) (PrivateKey, error) - - // SerializePrivateKey serializes a private key - SerializePublicKey(pub PublicKey) ([]byte, error) - - // DeserializePrivateKey deserializes to a private key - DeserializePublicKey(bytes []byte) (PublicKey, error) -} - -// StreamCipherSPI is a Service Provider Interface for StreamCipher -type StreamCipherSPI interface { - GenerateKey() (SecretKey, error) - - GenerateKeyAndSerialize() (SecretKey, []byte, error) - - NewSecretKey(rand io.Reader, params interface{}) (SecretKey, error) - - // NewStreamCipherForEncryptionFromKey creates a new StreamCipher for encryption from a secret key - NewStreamCipherForEncryptionFromKey(secret SecretKey) (StreamCipher, error) - - // NewStreamCipherForEncryptionFromSerializedKey creates a new StreamCipher for encryption from a serialized key - NewStreamCipherForEncryptionFromSerializedKey(secret []byte) (StreamCipher, error) - - // NewStreamCipherForDecryptionFromKey creates a new StreamCipher for decryption from a secret key - NewStreamCipherForDecryptionFromKey(secret SecretKey) (StreamCipher, error) - - // NewStreamCipherForDecryptionFromKey creates a new StreamCipher for decryption from a serialized key - NewStreamCipherForDecryptionFromSerializedKey(secret []byte) (StreamCipher, error) - - // SerializePrivateKey serializes a private key - SerializeSecretKey(secret SecretKey) ([]byte, error) - - // DeserializePrivateKey deserializes to a private key - DeserializeSecretKey(bytes []byte) (SecretKey, error) -} diff --git a/core/crypto/primitives/ecdsa.go b/core/crypto/primitives/ecdsa.go index 0550cea94d4..ed7aace3d1f 100644 --- a/core/crypto/primitives/ecdsa.go +++ b/core/crypto/primitives/ecdsa.go @@ -33,18 +33,6 @@ func NewECDSAKey() (*ecdsa.PrivateKey, error) { return ecdsa.GenerateKey(GetDefaultCurve(), rand.Reader) } -// ECDSASignDirect signs -func ECDSASignDirect(signKey interface{}, msg []byte) (*big.Int, *big.Int, error) { - temp := signKey.(*ecdsa.PrivateKey) - h := Hash(msg) - r, s, err := ecdsa.Sign(rand.Reader, temp, h) - if err != nil { - return nil, nil, err - } - - return r, s, nil -} - // ECDSASign signs func ECDSASign(signKey interface{}, msg []byte) ([]byte, error) { temp := signKey.(*ecdsa.PrivateKey) @@ -66,50 +54,3 @@ func ECDSASign(signKey interface{}, msg []byte) ([]byte, error) { return raw, nil } - -// ECDSAVerify verifies -func ECDSAVerify(verKey interface{}, msg, signature []byte) (bool, error) { - ecdsaSignature := new(ECDSASignature) - _, err := asn1.Unmarshal(signature, ecdsaSignature) - if err != nil { - return false, nil - } - - // R, _ := ecdsaSignature.R.MarshalText() - // S, _ := ecdsaSignature.S.MarshalText() - // fmt.Printf("r [%s], s [%s]\n", R, S) - - temp := verKey.(*ecdsa.PublicKey) - h := Hash(msg) - return ecdsa.Verify(temp, h, ecdsaSignature.R, ecdsaSignature.S), nil -} - -// VerifySignCapability tests signing capabilities -func VerifySignCapability(tempSK interface{}, certPK interface{}) error { - /* TODO: reactive or remove - msg := []byte("This is a message to be signed and verified by ECDSA!") - - sigma, err := ECDSASign(tempSK, msg) - if err != nil { - // log.Errorf("Error signing [%s].", err.Error()) - - return err - } - - ok, err := ECDSAVerify(certPK, msg, sigma) - if err != nil { - // log.Errorf("Error verifying [%s].", err.Error()) - - return err - } - - if !ok { - // log.Errorf("Signature not valid.") - - return errors.New("Signature not valid.") - } - - // log.Infof("Verifing signature capability...done") - */ - return nil -} diff --git a/core/crypto/primitives/ecies/engine.go b/core/crypto/primitives/ecies/engine.go deleted file mode 100644 index 8f0dd09972d..00000000000 --- a/core/crypto/primitives/ecies/engine.go +++ /dev/null @@ -1,218 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package ecies - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/hmac" - "crypto/rand" - "errors" - "io" - - "crypto/subtle" - "fmt" - - "github.com/hyperledger/fabric/core/crypto/primitives" - "golang.org/x/crypto/hkdf" -) - -func aesEncrypt(key, plain []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - - text := make([]byte, aes.BlockSize+len(plain)) - iv := text[:aes.BlockSize] - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - return nil, err - } - - cfb := cipher.NewCFBEncrypter(block, iv) - cfb.XORKeyStream(text[aes.BlockSize:], plain) - - return text, nil -} - -func aesDecrypt(key, text []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - - if len(text) < aes.BlockSize { - return nil, errors.New("cipher text too short") - } - - cfb := cipher.NewCFBDecrypter(block, text[:aes.BlockSize]) - plain := make([]byte, len(text)-aes.BlockSize) - cfb.XORKeyStream(plain, text[aes.BlockSize:]) - - return plain, nil -} - -func eciesGenerateKey(rand io.Reader, curve elliptic.Curve, params *Params) (*ecdsa.PrivateKey, error) { - return ecdsa.GenerateKey(curve, rand) -} - -func eciesEncrypt(rand io.Reader, pub *ecdsa.PublicKey, s1, s2 []byte, plain []byte) ([]byte, error) { - params := pub.Curve - - // Select an ephemeral elliptic curve key pair associated with - // elliptic curve domain parameters params - priv, Rx, Ry, err := elliptic.GenerateKey(pub.Curve, rand) - //fmt.Printf("Rx %s\n", utils.EncodeBase64(Rx.Bytes())) - //fmt.Printf("Ry %s\n", utils.EncodeBase64(Ry.Bytes())) - - // Convert R=(Rx,Ry) to an octed string R bar - // This is uncompressed - Rb := elliptic.Marshal(pub.Curve, Rx, Ry) - - // Derive a shared secret field element z from the ephemeral secret key k - // and convert z to an octet string Z - z, _ := params.ScalarMult(pub.X, pub.Y, priv) - Z := z.Bytes() - //fmt.Printf("Z %s\n", utils.EncodeBase64(Z)) - - // generate keying data K of length ecnKeyLen + macKeyLen octects from Z - // ans s1 - kE := make([]byte, 32) - kM := make([]byte, 32) - hkdf := hkdf.New(primitives.GetDefaultHash(), Z, s1, nil) - _, err = hkdf.Read(kE) - if err != nil { - return nil, err - } - _, err = hkdf.Read(kM) - if err != nil { - return nil, err - } - - // Use the encryption operation of the symmetric encryption scheme - // to encrypt m under EK as ciphertext EM - EM, err := aesEncrypt(kE, plain) - - // Use the tagging operation of the MAC scheme to compute - // the tag D on EM || s2 - mac := hmac.New(primitives.GetDefaultHash(), kM) - mac.Write(EM) - if len(s2) > 0 { - mac.Write(s2) - } - D := mac.Sum(nil) - - // Output R,EM,D - ciphertext := make([]byte, len(Rb)+len(EM)+len(D)) - //fmt.Printf("Rb %s\n", utils.EncodeBase64(Rb)) - //fmt.Printf("EM %s\n", utils.EncodeBase64(EM)) - //fmt.Printf("D %s\n", utils.EncodeBase64(D)) - copy(ciphertext, Rb) - copy(ciphertext[len(Rb):], EM) - copy(ciphertext[len(Rb)+len(EM):], D) - - return ciphertext, nil -} - -func eciesDecrypt(priv *ecdsa.PrivateKey, s1, s2 []byte, ciphertext []byte) ([]byte, error) { - params := priv.Curve - - var ( - rLen int - hLen = primitives.GetDefaultHash()().Size() - mStart int - mEnd int - ) - - //fmt.Printf("Decrypt\n") - switch ciphertext[0] { - case 2, 3: - rLen = ((priv.PublicKey.Curve.Params().BitSize + 7) / 8) + 1 - if len(ciphertext) < (rLen + hLen + 1) { - return nil, fmt.Errorf("Invalid ciphertext len [First byte = %d]", ciphertext[0]) - } - break - case 4: - rLen = 2*((priv.PublicKey.Curve.Params().BitSize+7)/8) + 1 - if len(ciphertext) < (rLen + hLen + 1) { - return nil, fmt.Errorf("Invalid ciphertext len [First byte = %d]", ciphertext[0]) - } - break - - default: - return nil, fmt.Errorf("Invalid ciphertext. Invalid first byte. [%d]", ciphertext[0]) - } - - mStart = rLen - mEnd = len(ciphertext) - hLen - //fmt.Printf("Rb %s\n", utils.EncodeBase64(ciphertext[:rLen])) - - Rx, Ry := elliptic.Unmarshal(priv.Curve, ciphertext[:rLen]) - if Rx == nil { - return nil, errors.New("Invalid ephemeral PK") - } - if !priv.Curve.IsOnCurve(Rx, Ry) { - return nil, errors.New("Invalid point on curve") - } - //fmt.Printf("Rx %s\n", utils.EncodeBase64(Rx.Bytes())) - //fmt.Printf("Ry %s\n", utils.EncodeBase64(Ry.Bytes())) - - // Derive a shared secret field element z from the ephemeral secret key k - // and convert z to an octet string Z - z, _ := params.ScalarMult(Rx, Ry, priv.D.Bytes()) - Z := z.Bytes() - //fmt.Printf("Z %s\n", utils.EncodeBase64(Z)) - - // generate keying data K of length ecnKeyLen + macKeyLen octects from Z - // ans s1 - kE := make([]byte, 32) - kM := make([]byte, 32) - hkdf := hkdf.New(primitives.GetDefaultHash(), Z, s1, nil) - _, err := hkdf.Read(kE) - if err != nil { - return nil, err - } - _, err = hkdf.Read(kM) - if err != nil { - return nil, err - } - - // Use the tagging operation of the MAC scheme to compute - // the tag D on EM || s2 and then compare - mac := hmac.New(primitives.GetDefaultHash(), kM) - mac.Write(ciphertext[mStart:mEnd]) - if len(s2) > 0 { - mac.Write(s2) - } - D := mac.Sum(nil) - - //fmt.Printf("EM %s\n", utils.EncodeBase64(ciphertext[mStart:mEnd])) - //fmt.Printf("D' %s\n", utils.EncodeBase64(D)) - //fmt.Printf("D %s\n", utils.EncodeBase64(ciphertext[mEnd:])) - if subtle.ConstantTimeCompare(ciphertext[mEnd:], D) != 1 { - return nil, errors.New("Tag check failed") - } - - // Use the decryption operation of the symmetric encryption scheme - // to decryptr EM under EK as plaintext - - plaintext, err := aesDecrypt(kE, ciphertext[mStart:mEnd]) - - return plaintext, err -} diff --git a/core/crypto/primitives/ecies/es.go b/core/crypto/primitives/ecies/es.go deleted file mode 100644 index 93c26ec6e06..00000000000 --- a/core/crypto/primitives/ecies/es.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package ecies - -import ( - "github.com/hyperledger/fabric/core/crypto/primitives" - "github.com/hyperledger/fabric/core/crypto/utils" -) - -type encryptionSchemeImpl struct { - isForEncryption bool - - // Parameters - params primitives.AsymmetricCipherParameters - pub *publicKeyImpl - priv *secretKeyImpl -} - -func (es *encryptionSchemeImpl) Init(params primitives.AsymmetricCipherParameters) error { - if params == nil { - return primitives.ErrInvalidNilKeyParameter - } - es.isForEncryption = params.IsPublic() - es.params = params - - if es.isForEncryption { - switch pk := params.(type) { - case *publicKeyImpl: - es.pub = pk - default: - return primitives.ErrInvalidPublicKeyType - } - } else { - switch sk := params.(type) { - case *secretKeyImpl: - es.priv = sk - default: - return primitives.ErrInvalidKeyParameter - } - } - - return nil -} - -func (es *encryptionSchemeImpl) Process(msg []byte) ([]byte, error) { - if len(msg) == 0 { - return nil, utils.ErrNilArgument - } - - if es.isForEncryption { - // Encrypt - return eciesEncrypt(es.params.GetRand(), es.pub.pub, nil, nil, msg) - } - - // Decrypt - return eciesDecrypt(es.priv.priv, nil, nil, msg) -} diff --git a/core/crypto/primitives/ecies/kg.go b/core/crypto/primitives/ecies/kg.go deleted file mode 100644 index 4fef5616b3a..00000000000 --- a/core/crypto/primitives/ecies/kg.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package ecies - -import ( - "crypto/elliptic" - "fmt" - "io" - - "github.com/hyperledger/fabric/core/crypto/primitives" -) - -type keyGeneratorParameterImpl struct { - rand io.Reader - curve elliptic.Curve - params *Params -} - -type keyGeneratorImpl struct { - isForEncryption bool - params *keyGeneratorParameterImpl -} - -func (kgp keyGeneratorParameterImpl) GetRand() io.Reader { - return kgp.rand -} - -func (kg *keyGeneratorImpl) Init(params primitives.KeyGeneratorParameters) error { - if params == nil { - return primitives.ErrInvalidKeyGeneratorParameter - } - switch kgparams := params.(type) { - case *keyGeneratorParameterImpl: - kg.params = kgparams - default: - return primitives.ErrInvalidKeyGeneratorParameter - } - - return nil -} - -func (kg *keyGeneratorImpl) GenerateKey() (primitives.PrivateKey, error) { - if kg.params == nil { - return nil, fmt.Errorf("Key Generator not initliazed") - } - - privKey, err := eciesGenerateKey( - kg.params.rand, - kg.params.curve, - kg.params.params, - ) - if err != nil { - return nil, err - } - - return &secretKeyImpl{privKey, nil, kg.params.params, kg.params.rand}, nil -} diff --git a/core/crypto/primitives/ecies/params.go b/core/crypto/primitives/ecies/params.go deleted file mode 100644 index de78fcef930..00000000000 --- a/core/crypto/primitives/ecies/params.go +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package ecies - -import ( - "crypto" - "crypto/cipher" - "hash" -) - -// Params ECIES parameters -type Params struct { - Hash func() hash.Hash - hashAlgo crypto.Hash - Cipher func([]byte) (cipher.Block, error) - BlockSize int - KeyLen int -} diff --git a/core/crypto/primitives/ecies/pk.go b/core/crypto/primitives/ecies/pk.go deleted file mode 100644 index a26d2f7b090..00000000000 --- a/core/crypto/primitives/ecies/pk.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package ecies - -import ( - "crypto/ecdsa" - "crypto/rand" - "crypto/x509" - "io" - - "github.com/hyperledger/fabric/core/crypto/primitives" -) - -type publicKeyImpl struct { - pub *ecdsa.PublicKey - rand io.Reader - params *Params -} - -func (pk *publicKeyImpl) GetRand() io.Reader { - return pk.rand -} - -func (pk *publicKeyImpl) IsPublic() bool { - return true -} - -type publicKeySerializerImpl struct{} - -func (pks *publicKeySerializerImpl) ToBytes(key interface{}) ([]byte, error) { - if key == nil { - return nil, primitives.ErrInvalidNilKeyParameter - } - - switch pk := key.(type) { - case *publicKeyImpl: - return x509.MarshalPKIXPublicKey(pk.pub) - default: - return nil, primitives.ErrInvalidPublicKeyType - } -} - -func (pks *publicKeySerializerImpl) FromBytes(bytes []byte) (interface{}, error) { - key, err := x509.ParsePKIXPublicKey(bytes) - if err != nil { - return nil, err - } - - // TODO: add params here - return &publicKeyImpl{key.(*ecdsa.PublicKey), rand.Reader, nil}, nil -} diff --git a/core/crypto/primitives/ecies/sk.go b/core/crypto/primitives/ecies/sk.go deleted file mode 100644 index 409e3c24dc6..00000000000 --- a/core/crypto/primitives/ecies/sk.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package ecies - -import ( - "crypto/ecdsa" - "crypto/rand" - "crypto/x509" - "io" - - "github.com/hyperledger/fabric/core/crypto/primitives" -) - -type secretKeyImpl struct { - priv *ecdsa.PrivateKey - pub primitives.PublicKey - params *Params - rand io.Reader -} - -func (sk *secretKeyImpl) IsPublic() bool { - return false -} - -func (sk *secretKeyImpl) GetRand() io.Reader { - return sk.rand -} - -func (sk *secretKeyImpl) GetPublicKey() primitives.PublicKey { - if sk.pub == nil { - sk.pub = &publicKeyImpl{&sk.priv.PublicKey, sk.rand, sk.params} - } - return sk.pub -} - -type secretKeySerializerImpl struct{} - -func (sks *secretKeySerializerImpl) ToBytes(key interface{}) ([]byte, error) { - if key == nil { - return nil, primitives.ErrInvalidNilKeyParameter - } - - switch sk := key.(type) { - case *secretKeyImpl: - return x509.MarshalECPrivateKey(sk.priv) - default: - return nil, primitives.ErrInvalidKeyParameter - } -} - -func (sks *secretKeySerializerImpl) FromBytes(bytes []byte) (interface{}, error) { - key, err := x509.ParseECPrivateKey(bytes) - if err != nil { - return nil, err - } - - // TODO: add params here - return &secretKeyImpl{key, nil, nil, rand.Reader}, nil -} diff --git a/core/crypto/primitives/ecies/spi.go b/core/crypto/primitives/ecies/spi.go deleted file mode 100644 index b991092a4d0..00000000000 --- a/core/crypto/primitives/ecies/spi.go +++ /dev/null @@ -1,258 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package ecies - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "fmt" - "io" - - "github.com/hyperledger/fabric/core/crypto/primitives" -) - -func newKeyGeneratorParameter(r io.Reader, curve elliptic.Curve) (primitives.KeyGeneratorParameters, error) { - if r == nil { - r = rand.Reader - } - return &keyGeneratorParameterImpl{r, curve, nil}, nil -} - -func newKeyGenerator() (primitives.KeyGenerator, error) { - return &keyGeneratorImpl{}, nil -} - -func newKeyGeneratorFromCurve(r io.Reader, curve elliptic.Curve) (primitives.KeyGenerator, error) { - if r == nil { - r = rand.Reader - } - if curve == nil { - curve = primitives.GetDefaultCurve() - } - - kg, err := newKeyGenerator() - if err != nil { - return nil, err - } - - kgp, err := newKeyGeneratorParameter(r, curve) - if err != nil { - return nil, err - } - - err = kg.Init(kgp) - if err != nil { - return nil, err - } - - return kg, nil -} - -func newPublicKeyFromECDSA(r io.Reader, pk *ecdsa.PublicKey) (primitives.PublicKey, error) { - if r == nil { - r = rand.Reader - } - if pk == nil { - return nil, fmt.Errorf("Null ECDSA public key") - } - - return &publicKeyImpl{pk, r, nil}, nil -} - -func newPrivateKeyFromECDSA(r io.Reader, sk *ecdsa.PrivateKey) (primitives.PrivateKey, error) { - if r == nil { - r = rand.Reader - } - if sk == nil { - return nil, fmt.Errorf("Null ECDSA secret key") - } - - return &secretKeyImpl{sk, nil, nil, r}, nil -} - -func serializePrivateKey(priv primitives.PrivateKey) ([]byte, error) { - if priv == nil { - return nil, fmt.Errorf("Null Private Key") - } - - serializer := secretKeySerializerImpl{} - return serializer.ToBytes(priv) -} - -func deserializePrivateKey(bytes []byte) (primitives.PrivateKey, error) { - if len(bytes) == 0 { - return nil, fmt.Errorf("Null bytes") - } - - serializer := secretKeySerializerImpl{} - priv, err := serializer.FromBytes(bytes) - if err != nil { - return nil, err - } - - return priv.(primitives.PrivateKey), nil -} - -func serializePublicKey(pub primitives.PublicKey) ([]byte, error) { - if pub == nil { - return nil, fmt.Errorf("Null Public Key") - } - - serializer := publicKeySerializerImpl{} - return serializer.ToBytes(pub) -} - -func deserializePublicKey(bytes []byte) (primitives.PublicKey, error) { - if len(bytes) == 0 { - return nil, fmt.Errorf("Null bytes") - } - - serializer := publicKeySerializerImpl{} - pub, err := serializer.FromBytes(bytes) - if err != nil { - return nil, err - } - - return pub.(primitives.PublicKey), nil -} - -func newAsymmetricCipher() (primitives.AsymmetricCipher, error) { - return &encryptionSchemeImpl{}, nil -} - -func newPrivateKey(r io.Reader, curve elliptic.Curve) (primitives.PrivateKey, error) { - if r == nil { - r = rand.Reader - } - if curve == nil { - curve = primitives.GetDefaultCurve() - } - kg, err := newKeyGeneratorFromCurve(r, curve) - if err != nil { - return nil, err - } - return kg.GenerateKey() -} - -func newAsymmetricCipherFromPrivateKey(priv primitives.PrivateKey) (primitives.AsymmetricCipher, error) { - if priv == nil { - return nil, fmt.Errorf("Null Private Key") - } - - es, err := newAsymmetricCipher() - if err != nil { - return nil, err - } - - err = es.Init(priv) - if err != nil { - return nil, err - } - - return es, nil -} - -func newAsymmetricCipherFromPublicKey(pub primitives.PublicKey) (primitives.AsymmetricCipher, error) { - if pub == nil { - return nil, fmt.Errorf("Null Public Key") - } - - es, err := newAsymmetricCipher() - if err != nil { - return nil, err - } - - err = es.Init(pub) - if err != nil { - return nil, err - } - - return es, nil -} - -// NewSPI returns a new SPI instance -func NewSPI() primitives.AsymmetricCipherSPI { - return &spiImpl{} -} - -type spiImpl struct { -} - -func (spi *spiImpl) NewAsymmetricCipherFromPrivateKey(priv primitives.PrivateKey) (primitives.AsymmetricCipher, error) { - return newAsymmetricCipherFromPrivateKey(priv) -} - -func (spi *spiImpl) NewAsymmetricCipherFromPublicKey(pub primitives.PublicKey) (primitives.AsymmetricCipher, error) { - return newAsymmetricCipherFromPublicKey(pub) -} - -func (spi *spiImpl) NewAsymmetricCipherFromSerializedPublicKey(pub []byte) (primitives.AsymmetricCipher, error) { - pk, err := spi.DeserializePublicKey(pub) - if err != nil { - return nil, err - } - return newAsymmetricCipherFromPublicKey(pk) -} - -func (spi *spiImpl) NewAsymmetricCipherFromSerializedPrivateKey(priv []byte) (primitives.AsymmetricCipher, error) { - sk, err := spi.DeserializePrivateKey(priv) - if err != nil { - return nil, err - } - return newAsymmetricCipherFromPrivateKey(sk) -} - -func (spi *spiImpl) NewPrivateKey(r io.Reader, params interface{}) (primitives.PrivateKey, error) { - switch t := params.(type) { - case *ecdsa.PrivateKey: - return newPrivateKeyFromECDSA(r, t) - case elliptic.Curve: - return newPrivateKey(r, t) - default: - return nil, primitives.ErrInvalidKeyGeneratorParameter - } -} - -func (spi *spiImpl) NewDefaultPrivateKey(r io.Reader) (primitives.PrivateKey, error) { - return spi.NewPrivateKey(r, primitives.GetDefaultCurve()) -} - -func (spi *spiImpl) NewPublicKey(r io.Reader, params interface{}) (primitives.PublicKey, error) { - switch t := params.(type) { - case *ecdsa.PublicKey: - return newPublicKeyFromECDSA(r, t) - default: - return nil, primitives.ErrInvalidKeyGeneratorParameter - } -} - -func (spi *spiImpl) SerializePrivateKey(priv primitives.PrivateKey) ([]byte, error) { - return serializePrivateKey(priv) -} - -func (spi *spiImpl) DeserializePrivateKey(bytes []byte) (primitives.PrivateKey, error) { - return deserializePrivateKey(bytes) -} - -func (spi *spiImpl) SerializePublicKey(priv primitives.PublicKey) ([]byte, error) { - return serializePublicKey(priv) -} - -func (spi *spiImpl) DeserializePublicKey(bytes []byte) (primitives.PublicKey, error) { - return deserializePublicKey(bytes) -} diff --git a/core/crypto/primitives/ecies/spi_test.go b/core/crypto/primitives/ecies/spi_test.go deleted file mode 100644 index 593f0a395eb..00000000000 --- a/core/crypto/primitives/ecies/spi_test.go +++ /dev/null @@ -1,310 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package ecies - -import ( - "crypto/ecdsa" - "crypto/rand" - "fmt" - "os" - "reflect" - "testing" - - "github.com/hyperledger/fabric/core/crypto/primitives" -) - -type TestParameters struct { - hashFamily string - securityLevel int -} - -func (t *TestParameters) String() string { - return t.hashFamily + "-" + string(t.securityLevel) -} - -var testParametersSet = []*TestParameters{ - &TestParameters{"SHA3", 256}, - &TestParameters{"SHA3", 384}, - &TestParameters{"SHA2", 256}, - &TestParameters{"SHA2", 384}} - -func TestMain(m *testing.M) { - for _, params := range testParametersSet { - err := primitives.SetSecurityLevel(params.hashFamily, params.securityLevel) - if err == nil { - m.Run() - } else { - panic(fmt.Errorf("Failed initiliazing crypto layer at [%s]", params.String())) - } - } - os.Exit(0) -} - -func TestSPINewDefaultPrivateKey(t *testing.T) { - spi := NewSPI() - - if _, err := spi.NewDefaultPrivateKey(rand.Reader); err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - if _, err := spi.NewDefaultPrivateKey(nil); err != nil { - t.Fatalf("Failed generating key [%s]", err) - } -} - -func TestSPINewPrivateKeyFromCurve(t *testing.T) { - spi := NewSPI() - - if _, err := spi.NewPrivateKey(rand.Reader, primitives.GetDefaultCurve()); err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - if _, err := spi.NewPrivateKey(nil, primitives.GetDefaultCurve()); err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - if _, err := spi.NewPrivateKey(nil, nil); err == nil { - t.Fatalf("Generating key should file with nil params.") - } -} - -func TestSPINewPrivateKeyFromECDSAKey(t *testing.T) { - spi := NewSPI() - - ecdsaKey, err := ecdsa.GenerateKey(primitives.GetDefaultCurve(), rand.Reader) - if err != nil { - t.Fatalf("Failed generating ECDSA key [%s]", err) - } - - if _, err := spi.NewPrivateKey(rand.Reader, ecdsaKey); err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - if _, err := spi.NewPrivateKey(nil, ecdsaKey); err != nil { - t.Fatalf("Failed generating key [%s]", err) - } -} - -func TestSPINewPublicKeyFromECDSAKey(t *testing.T) { - spi := NewSPI() - - ecdsaKey, err := ecdsa.GenerateKey(primitives.GetDefaultCurve(), rand.Reader) - if err != nil { - t.Fatalf("Failed generating ECDSA key [%s]", err) - } - - if _, err := spi.NewPublicKey(rand.Reader, &ecdsaKey.PublicKey); err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - if _, err := spi.NewPublicKey(nil, &ecdsaKey.PublicKey); err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - if _, err := spi.NewPublicKey(nil, nil); err == nil { - t.Fatalf("Generating key should file with nil params.") - } -} - -func TestSPINewAsymmetricCipherFrom(t *testing.T) { - spi := NewSPI() - - key, err := spi.NewDefaultPrivateKey(nil) - if err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - if _, err := spi.NewAsymmetricCipherFromPrivateKey(key); err != nil { - t.Fatalf("Failed creating AsymCipher from private key [%s]", err) - } - - if _, err := spi.NewAsymmetricCipherFromPrivateKey(nil); err == nil { - t.Fatalf("Creating AsymCipher from private key shoud fail with nil key") - } - - if _, err := spi.NewAsymmetricCipherFromPublicKey(key.GetPublicKey()); err != nil { - t.Fatalf("Failed creating AsymCipher from public key [%s]", err) - } - - if _, err := spi.NewAsymmetricCipherFromPublicKey(nil); err == nil { - t.Fatalf("Creating AsymCipher from public key shoud fail with nil key") - } -} - -func TestSPIEncryption(t *testing.T) { - spi := NewSPI() - - key, err := spi.NewDefaultPrivateKey(nil) - if err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - // Encrypt - aCipher, err := spi.NewAsymmetricCipherFromPublicKey(key.GetPublicKey()) - if err != nil { - t.Fatalf("Failed creating AsymCipher from public key [%s]", err) - } - msg := []byte("Hello World") - ct, err := aCipher.Process(msg) - if err != nil { - t.Fatalf("Failed encrypting [%s]", err) - } - - // Decrypt - aCipher, err = spi.NewAsymmetricCipherFromPublicKey(key) - if err != nil { - t.Fatalf("Failed creating AsymCipher from private key [%s]", err) - } - recoveredMsg, err := aCipher.Process(ct) - if err != nil { - t.Fatalf("Failed decrypting [%s]", err) - } - if !reflect.DeepEqual(msg, recoveredMsg) { - t.Fatalf("Failed decrypting. Output is different [%x][%x]", msg, recoveredMsg) - } -} - -func TestSPIStressEncryption(t *testing.T) { - spi := NewSPI() - - key, err := spi.NewDefaultPrivateKey(nil) - if err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - // Encrypt - aCipher, err := spi.NewAsymmetricCipherFromPublicKey(key.GetPublicKey()) - if err != nil { - t.Fatalf("Failed creating AsymCipher from public key [%s]", err) - } - _, err = aCipher.Process(nil) - if err == nil { - t.Fatalf("Encrypting nil should fail") - } - -} - -func TestSPIStressDecryption(t *testing.T) { - spi := NewSPI() - - key, err := spi.NewDefaultPrivateKey(nil) - if err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - // Decrypt - aCipher, err := spi.NewAsymmetricCipherFromPublicKey(key) - if err != nil { - t.Fatalf("Failed creating AsymCipher from private key [%s]", err) - } - _, err = aCipher.Process(nil) - if err == nil { - t.Fatalf("Decrypting nil should fail") - } - - _, err = aCipher.Process([]byte{0, 1, 2, 3}) - if err == nil { - t.Fatalf("Decrypting invalid ciphertxt should fail") - } - -} - -func TestPrivateKeySerialization(t *testing.T) { - spi := NewSPI() - - aKey, err := spi.NewDefaultPrivateKey(rand.Reader) - if err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - bytes, err := spi.SerializePrivateKey(aKey) - if err != nil { - t.Fatalf("Failed serializing private key [%s]", err) - } - - recoveredKey, err := spi.DeserializePrivateKey(bytes) - if err != nil { - t.Fatalf("Failed serializing private key [%s]", err) - } - - // Encrypt - aCipher, err := spi.NewAsymmetricCipherFromPublicKey(aKey.GetPublicKey()) - if err != nil { - t.Fatalf("Failed creating AsymCipher from public key [%s]", err) - } - msg := []byte("Hello World") - ct, err := aCipher.Process(msg) - if err != nil { - t.Fatalf("Failed encrypting [%s]", err) - } - - // Decrypt - aCipher, err = spi.NewAsymmetricCipherFromPublicKey(recoveredKey) - if err != nil { - t.Fatalf("Failed creating AsymCipher from private key [%s]", err) - } - recoveredMsg, err := aCipher.Process(ct) - if err != nil { - t.Fatalf("Failed decrypting [%s]", err) - } - if !reflect.DeepEqual(msg, recoveredMsg) { - t.Fatalf("Failed decrypting. Output is different [%x][%x]", msg, recoveredMsg) - } -} - -func TestPublicKeySerialization(t *testing.T) { - spi := NewSPI() - - aKey, err := spi.NewDefaultPrivateKey(rand.Reader) - if err != nil { - t.Fatalf("Failed generating key [%s]", err) - } - - bytes, err := spi.SerializePublicKey(aKey.GetPublicKey()) - if err != nil { - t.Fatalf("Failed serializing private key [%s]", err) - } - - pk, err := spi.DeserializePublicKey(bytes) - if err != nil { - t.Fatalf("Failed serializing private key [%s]", err) - } - - // Encrypt - aCipher, err := spi.NewAsymmetricCipherFromPublicKey(pk) - if err != nil { - t.Fatalf("Failed creating AsymCipher from public key [%s]", err) - } - msg := []byte("Hello World") - ct, err := aCipher.Process(msg) - if err != nil { - t.Fatalf("Failed encrypting [%s]", err) - } - - // Decrypt - aCipher, err = spi.NewAsymmetricCipherFromPublicKey(aKey) - if err != nil { - t.Fatalf("Failed creating AsymCipher from private key [%s]", err) - } - recoveredMsg, err := aCipher.Process(ct) - if err != nil { - t.Fatalf("Failed decrypting [%s]", err) - } - if !reflect.DeepEqual(msg, recoveredMsg) { - t.Fatalf("Failed decrypting. Output is different [%x][%x]", msg, recoveredMsg) - } -} diff --git a/core/crypto/primitives/init.go b/core/crypto/primitives/init.go index bb88d972dad..b42a4f5f57f 100644 --- a/core/crypto/primitives/init.go +++ b/core/crypto/primitives/init.go @@ -36,11 +36,9 @@ func initSHA2(level int) (err error) { case 256: defaultCurve = elliptic.P256() defaultHash = sha256.New - defaultRSABitSize = 2048 case 384: defaultCurve = elliptic.P384() defaultHash = sha512.New384 - defaultRSABitSize = 3072 default: err = fmt.Errorf("Security level not supported [%d]", level) } @@ -53,11 +51,9 @@ func initSHA3(level int) (err error) { case 256: defaultCurve = elliptic.P256() defaultHash = sha3.New256 - defaultRSABitSize = 2048 case 384: defaultCurve = elliptic.P384() defaultHash = sha3.New384 - defaultRSABitSize = 3072 default: err = fmt.Errorf("Security level not supported [%d]", level) } diff --git a/core/crypto/primitives/keys.go b/core/crypto/primitives/keys.go index e635b2734bc..ab690d4e8bb 100644 --- a/core/crypto/primitives/keys.go +++ b/core/crypto/primitives/keys.go @@ -17,166 +17,17 @@ limitations under the License. package primitives import ( - "crypto/ecdsa" "crypto/rand" - "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "fmt" - - "github.com/hyperledger/fabric/core/crypto/utils" ) -// PrivateKeyToDER marshals a private key to der -func PrivateKeyToDER(privateKey *ecdsa.PrivateKey) ([]byte, error) { - if privateKey == nil { - return nil, utils.ErrNilArgument - } - - return x509.MarshalECPrivateKey(privateKey) -} - -// PrivateKeyToPEM converts a private key to PEM -func PrivateKeyToPEM(privateKey interface{}, pwd []byte) ([]byte, error) { - // Validate inputs - if len(pwd) != 0 { - return PrivateKeyToEncryptedPEM(privateKey, pwd) - } - - switch k := privateKey.(type) { - case *ecdsa.PrivateKey: - if k == nil { - return nil, errors.New("Invalid private key. It must be different from nil.") - } - - raw, err := x509.MarshalECPrivateKey(k) - - if err != nil { - return nil, err - } - - return pem.EncodeToMemory( - &pem.Block{ - Type: "ECDSA PRIVATE KEY", - Bytes: raw, - }, - ), nil - case *rsa.PrivateKey: - if k == nil { - return nil, errors.New("Invalid private key. It must be different from nil.") - } - - raw := x509.MarshalPKCS1PrivateKey(k) - - return pem.EncodeToMemory( - &pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: raw, - }, - ), nil - default: - return nil, utils.ErrInvalidKey - } -} - -// PrivateKeyToEncryptedPEM converts a private key to an encrypted PEM -func PrivateKeyToEncryptedPEM(privateKey interface{}, pwd []byte) ([]byte, error) { - switch k := privateKey.(type) { - case *ecdsa.PrivateKey: - if k == nil { - return nil, errors.New("Invalid private key. It must be different from nil.") - } - - raw, err := x509.MarshalECPrivateKey(k) - - if err != nil { - return nil, err - } - - block, err := x509.EncryptPEMBlock( - rand.Reader, - "ECDSA PRIVATE KEY", - raw, - pwd, - x509.PEMCipherAES256) - - if err != nil { - return nil, err - } - - return pem.EncodeToMemory(block), nil - - default: - return nil, utils.ErrInvalidKey - } -} - -// DERToPrivateKey unmarshals a der to private key -func DERToPrivateKey(der []byte) (key interface{}, err error) { - //fmt.Printf("DER [%s]\n", EncodeBase64(der)) - - if key, err = x509.ParsePKCS1PrivateKey(der); err == nil { - return key, nil - } - //fmt.Printf("DERToPrivateKey Err [%s]\n", err) - if key, err = x509.ParsePKCS8PrivateKey(der); err == nil { - switch key.(type) { - case *rsa.PrivateKey, *ecdsa.PrivateKey: - return - default: - return nil, errors.New("Found unknown private key type in PKCS#8 wrapping") - } - } - //fmt.Printf("DERToPrivateKey Err [%s]\n", err) - if key, err = x509.ParseECPrivateKey(der); err == nil { - return - } - //fmt.Printf("DERToPrivateKey Err [%s]\n", err) - - return nil, errors.New("Failed to parse private key") -} - -// PEMtoPrivateKey unmarshals a pem to private key -func PEMtoPrivateKey(raw []byte, pwd []byte) (interface{}, error) { - if len(raw) == 0 { - return nil, utils.ErrNilArgument - } - block, _ := pem.Decode(raw) - if block == nil { - return nil, fmt.Errorf("Failed decoding [% x]", raw) - } - - // TODO: derive from header the type of the key - - if x509.IsEncryptedPEMBlock(block) { - if len(pwd) == 0 { - return nil, errors.New("Encrypted Key. Need a password!!!") - } - - decrypted, err := x509.DecryptPEMBlock(block, pwd) - if err != nil { - return nil, errors.New("Failed decryption!!!") - } - - key, err := DERToPrivateKey(decrypted) - if err != nil { - return nil, err - } - return key, err - } - - cert, err := DERToPrivateKey(block.Bytes) - if err != nil { - return nil, err - } - return cert, err -} - // PEMtoAES extracts from the PEM an AES key func PEMtoAES(raw []byte, pwd []byte) ([]byte, error) { if len(raw) == 0 { - return nil, utils.ErrNilArgument + return nil, errors.New("Invalid PEM. It must be different from nil") } block, _ := pem.Decode(raw) if block == nil { @@ -225,146 +76,3 @@ func AEStoEncryptedPEM(raw []byte, pwd []byte) ([]byte, error) { return pem.EncodeToMemory(block), nil } - -/* -func PublicKeyToDER(publicKey interface{}) ([]byte, error) { - return x509.MarshalPKIXPublicKey(publicKey) -} - -func DERToPublicKey(derBytes []byte) (pub interface{}, err error) { - key, err := x509.ParsePKIXPublicKey(derBytes) - - return key, err -} -*/ - -// PublicKeyToPEM marshals a public key to the pem format -func PublicKeyToPEM(publicKey interface{}, pwd []byte) ([]byte, error) { - if len(pwd) != 0 { - return PublicKeyToEncryptedPEM(publicKey, pwd) - } - - switch k := publicKey.(type) { - case *ecdsa.PublicKey: - if k == nil { - return nil, errors.New("Invalid private key. It must be different from nil.") - } - - PubASN1, err := x509.MarshalPKIXPublicKey(k) - if err != nil { - return nil, err - } - - return pem.EncodeToMemory( - &pem.Block{ - Type: "ECDSA PUBLIC KEY", - Bytes: PubASN1, - }, - ), nil - case *rsa.PublicKey: - if k == nil { - return nil, errors.New("Invalid private key. It must be different from nil.") - } - - PubASN1, err := x509.MarshalPKIXPublicKey(k) - if err != nil { - return nil, err - } - - return pem.EncodeToMemory( - &pem.Block{ - Type: "RSA PUBLIC KEY", - Bytes: PubASN1, - }, - ), nil - - default: - return nil, utils.ErrInvalidKey - } -} - -// PublicKeyToDER marshals a public key to the der format -func PublicKeyToDER(publicKey interface{}) ([]byte, error) { - switch x := publicKey.(type) { - case *ecdsa.PublicKey: - PubASN1, err := x509.MarshalPKIXPublicKey(x) - if err != nil { - return nil, err - } - - return PubASN1, nil - - default: - return nil, utils.ErrInvalidKey - } -} - -// PublicKeyToEncryptedPEM converts a public key to encrypted pem -func PublicKeyToEncryptedPEM(publicKey interface{}, pwd []byte) ([]byte, error) { - switch x := publicKey.(type) { - case *ecdsa.PublicKey: - raw, err := x509.MarshalPKIXPublicKey(x) - - if err != nil { - return nil, err - } - - block, err := x509.EncryptPEMBlock( - rand.Reader, - "ECDSA PUBLIC KEY", - raw, - pwd, - x509.PEMCipherAES256) - - if err != nil { - return nil, err - } - - return pem.EncodeToMemory(block), nil - - default: - return nil, utils.ErrInvalidKey - } -} - -// PEMtoPublicKey unmarshals a pem to public key -func PEMtoPublicKey(raw []byte, pwd []byte) (interface{}, error) { - if len(raw) == 0 { - return nil, utils.ErrNilArgument - } - block, _ := pem.Decode(raw) - if block == nil { - return nil, fmt.Errorf("Failed decoding [% x]", raw) - } - - // TODO: derive from header the type of the key - if x509.IsEncryptedPEMBlock(block) { - if len(pwd) == 0 { - return nil, errors.New("Encrypted Key. Need a password!!!") - } - - decrypted, err := x509.DecryptPEMBlock(block, pwd) - if err != nil { - return nil, errors.New("Failed decryption!!!") - } - - key, err := DERToPublicKey(decrypted) - if err != nil { - return nil, err - } - return key, err - } - - cert, err := DERToPublicKey(block.Bytes) - if err != nil { - return nil, err - } - return cert, err -} - -// DERToPublicKey unmarshals a der to public key -func DERToPublicKey(derBytes []byte) (pub interface{}, err error) { - key, err := x509.ParsePKIXPublicKey(derBytes) - - return key, err -} diff --git a/core/crypto/primitives/primitives_test.go b/core/crypto/primitives/primitives_test.go deleted file mode 100644 index 4ed166555b2..00000000000 --- a/core/crypto/primitives/primitives_test.go +++ /dev/null @@ -1,421 +0,0 @@ -package primitives - -import ( - "crypto/ecdsa" - "crypto/rand" - "encoding/asn1" - "fmt" - "math/big" - "os" - "reflect" - "testing" -) - -type TestParameters struct { - hashFamily string - securityLevel int -} - -func (t *TestParameters) String() string { - return t.hashFamily + "-" + string(t.securityLevel) -} - -var testParametersSet = []*TestParameters{ - &TestParameters{"SHA3", 256}, - &TestParameters{"SHA3", 384}, - &TestParameters{"SHA2", 256}, - &TestParameters{"SHA2", 384}} - -func TestMain(m *testing.M) { - for _, params := range testParametersSet { - err := InitSecurityLevel(params.hashFamily, params.securityLevel) - if err == nil { - m.Run() - } else { - panic(fmt.Errorf("Failed initiliazing crypto layer at [%s]", params.String())) - } - - err = SetSecurityLevel(params.hashFamily, params.securityLevel) - if err == nil { - m.Run() - } else { - panic(fmt.Errorf("Failed initiliazing crypto layer at [%s]", params.String())) - } - - if GetHashAlgorithm() != params.hashFamily { - panic(fmt.Errorf("Failed initiliazing crypto layer. Invalid Hash family [%s][%s]", GetHashAlgorithm(), params.hashFamily)) - } - - } - os.Exit(0) -} - -func TestInitSecurityLevel(t *testing.T) { - err := SetSecurityLevel("SHA2", 1024) - if err == nil { - t.Fatalf("Initialization should fail") - } - - err = SetSecurityLevel("SHA", 1024) - if err == nil { - t.Fatalf("Initialization should fail") - } - - err = SetSecurityLevel("SHA3", 2048) - if err == nil { - t.Fatalf("Initialization should fail") - } -} - -func TestECDSA(t *testing.T) { - - key, err := NewECDSAKey() - if err != nil { - t.Fatalf("Failed generating ECDSA key [%s]", err) - } - - for i := 1; i < 100; i++ { - length, err := rand.Int(rand.Reader, big.NewInt(1024)) - if err != nil { - t.Fatalf("Failed generating AES key [%s]", err) - } - msg, err := GetRandomBytes(int(length.Int64()) + 1) - if err != nil { - t.Fatalf("Failed generating AES key [%s]", err) - } - - sigma, err := ECDSASign(key, msg) - if err != nil { - t.Fatalf("Failed signing [%s]", err) - } - - ok, err := ECDSAVerify(key.Public(), msg, sigma) - if err != nil { - t.Fatalf("Failed verifying [%s]", err) - } - if !ok { - t.Fatalf("Failed verification.") - } - - ok, err = ECDSAVerify(key.Public(), msg[:len(msg)-1], sigma) - if err != nil { - t.Fatalf("Failed verifying [%s]", err) - } - if ok { - t.Fatalf("Verification should fail.") - } - - ok, err = ECDSAVerify(key.Public(), msg[:1], sigma[:1]) - if err != nil { - t.Fatalf("Failed verifying [%s]", err) - } - if ok { - t.Fatalf("Verification should fail.") - } - - R, S, err := ECDSASignDirect(key, msg) - if err != nil { - t.Fatalf("Failed signing (direct) [%s]", err) - } - if sigma, err = asn1.Marshal(ECDSASignature{R, S}); err != nil { - t.Fatalf("Failed marshalling (R,S) [%s]", err) - } - ok, err = ECDSAVerify(key.Public(), msg, sigma) - if err != nil { - t.Fatalf("Failed verifying [%s]", err) - } - if !ok { - t.Fatalf("Failed verification.") - } - } -} - -func TestECDSAKeys(t *testing.T) { - key, err := NewECDSAKey() - if err != nil { - t.Fatalf("Failed generating ECDSA key [%s]", err) - } - - // Private Key DER format - der, err := PrivateKeyToDER(key) - if err != nil { - t.Fatalf("Failed converting private key to DER [%s]", err) - } - keyFromDER, err := DERToPrivateKey(der) - if err != nil { - t.Fatalf("Failed converting DER to private key [%s]", err) - } - ecdsaKeyFromDer := keyFromDER.(*ecdsa.PrivateKey) - // TODO: check the curve - if key.D.Cmp(ecdsaKeyFromDer.D) != 0 { - t.Fatalf("Failed converting DER to private key. Invalid D.") - } - if key.X.Cmp(ecdsaKeyFromDer.X) != 0 { - t.Fatalf("Failed converting DER to private key. Invalid X coordinate.") - } - if key.Y.Cmp(ecdsaKeyFromDer.Y) != 0 { - t.Fatalf("Failed converting DER to private key. Invalid Y coordinate.") - } - - // Private Key PEM format - pem, err := PrivateKeyToPEM(key, nil) - if err != nil { - t.Fatalf("Failed converting private key to PEM [%s]", err) - } - keyFromPEM, err := PEMtoPrivateKey(pem, nil) - if err != nil { - t.Fatalf("Failed converting DER to private key [%s]", err) - } - ecdsaKeyFromPEM := keyFromPEM.(*ecdsa.PrivateKey) - // TODO: check the curve - if key.D.Cmp(ecdsaKeyFromPEM.D) != 0 { - t.Fatalf("Failed converting PEM to private key. Invalid D.") - } - if key.X.Cmp(ecdsaKeyFromPEM.X) != 0 { - t.Fatalf("Failed converting PEM to private key. Invalid X coordinate.") - } - if key.Y.Cmp(ecdsaKeyFromPEM.Y) != 0 { - t.Fatalf("Failed converting PEM to private key. Invalid Y coordinate.") - } - - // Nil Private Key <-> PEM - _, err = PrivateKeyToPEM(nil, nil) - if err == nil { - t.Fatalf("PublicKeyToPEM should fail on nil") - } - - _, err = PEMtoPrivateKey(nil, nil) - if err == nil { - t.Fatalf("PEMtoPublicKey should fail on nil") - } - - _, err = PEMtoPrivateKey([]byte{0, 1, 3, 4}, nil) - if err == nil { - t.Fatalf("PEMtoPublicKey should fail invalid PEM") - } - - _, err = DERToPrivateKey(nil) - if err == nil { - t.Fatalf("DERToPrivateKey should fail on nil") - } - - _, err = DERToPrivateKey([]byte{0, 1, 3, 4}) - if err == nil { - t.Fatalf("DERToPrivateKey should fail on invalid DER") - } - - _, err = PrivateKeyToDER(nil) - if err == nil { - t.Fatalf("DERToPrivateKey should fail on nil") - } - - // Private Key Encrypted PEM format - encPEM, err := PrivateKeyToPEM(key, []byte("passwd")) - if err != nil { - t.Fatalf("Failed converting private key to encrypted PEM [%s]", err) - } - encKeyFromPEM, err := PEMtoPrivateKey(encPEM, []byte("passwd")) - if err != nil { - t.Fatalf("Failed converting DER to private key [%s]", err) - } - ecdsaKeyFromEncPEM := encKeyFromPEM.(*ecdsa.PrivateKey) - // TODO: check the curve - if key.D.Cmp(ecdsaKeyFromEncPEM.D) != 0 { - t.Fatalf("Failed converting encrypted PEM to private key. Invalid D.") - } - if key.X.Cmp(ecdsaKeyFromEncPEM.X) != 0 { - t.Fatalf("Failed converting encrypted PEM to private key. Invalid X coordinate.") - } - if key.Y.Cmp(ecdsaKeyFromEncPEM.Y) != 0 { - t.Fatalf("Failed converting encrypted PEM to private key. Invalid Y coordinate.") - } - - // Public Key PEM format - pem, err = PublicKeyToPEM(&key.PublicKey, nil) - if err != nil { - t.Fatalf("Failed converting public key to PEM [%s]", err) - } - keyFromPEM, err = PEMtoPublicKey(pem, nil) - if err != nil { - t.Fatalf("Failed converting DER to public key [%s]", err) - } - ecdsaPkFromPEM := keyFromPEM.(*ecdsa.PublicKey) - // TODO: check the curve - if key.X.Cmp(ecdsaPkFromPEM.X) != 0 { - t.Fatalf("Failed converting PEM to private key. Invalid X coordinate.") - } - if key.Y.Cmp(ecdsaPkFromPEM.Y) != 0 { - t.Fatalf("Failed converting PEM to private key. Invalid Y coordinate.") - } - - // Nil Public Key <-> PEM - _, err = PublicKeyToPEM(nil, nil) - if err == nil { - t.Fatalf("PublicKeyToPEM should fail on nil") - } - - _, err = PEMtoPublicKey(nil, nil) - if err == nil { - t.Fatalf("PEMtoPublicKey should fail on nil") - } - - _, err = PEMtoPublicKey([]byte{0, 1, 3, 4}, nil) - if err == nil { - t.Fatalf("PEMtoPublicKey should fail on invalid PEM") - } - - // Public Key Encrypted PEM format - encPEM, err = PublicKeyToPEM(&key.PublicKey, []byte("passwd")) - if err != nil { - t.Fatalf("Failed converting private key to encrypted PEM [%s]", err) - } - pkFromEncPEM, err := PEMtoPublicKey(encPEM, []byte("passwd")) - if err != nil { - t.Fatalf("Failed converting DER to private key [%s]", err) - } - ecdsaPkFromEncPEM := pkFromEncPEM.(*ecdsa.PublicKey) - // TODO: check the curve - if key.X.Cmp(ecdsaPkFromEncPEM.X) != 0 { - t.Fatalf("Failed converting encrypted PEM to private key. Invalid X coordinate.") - } - if key.Y.Cmp(ecdsaPkFromEncPEM.Y) != 0 { - t.Fatalf("Failed converting encrypted PEM to private key. Invalid Y coordinate.") - } - - _, err = PEMtoPublicKey(encPEM, []byte("passw")) - if err == nil { - t.Fatalf("PEMtoPublicKey should fail on wrong password") - } - - _, err = PEMtoPublicKey(encPEM, []byte("passw")) - if err == nil { - t.Fatalf("PEMtoPublicKey should fail on nil password") - } - - _, err = PEMtoPublicKey(nil, []byte("passwd")) - if err == nil { - t.Fatalf("PEMtoPublicKey should fail on nil PEM") - } - - _, err = PEMtoPublicKey([]byte{0, 1, 3, 4}, []byte("passwd")) - if err == nil { - t.Fatalf("PEMtoPublicKey should fail on invalid PEM") - } - - _, err = PEMtoPublicKey(nil, []byte("passw")) - if err == nil { - t.Fatalf("PEMtoPublicKey should fail on nil PEM and wrong password") - } -} - -func TestRandom(t *testing.T) { - nonce, err := GetRandomNonce() - if err != nil { - t.Fatalf("Failed getting nonce [%s]", err) - } - - if len(nonce) != NonceSize { - t.Fatalf("Invalid nonce size. Expecting [%d], was [%d]", NonceSize, len(nonce)) - } -} - -func TestHMAC(t *testing.T) { - key, err := GenAESKey() - if err != nil { - t.Fatalf("Failed generating AES key [%s]", err) - } - - for i := 1; i < 100; i++ { - len, err := rand.Int(rand.Reader, big.NewInt(1024)) - if err != nil { - t.Fatalf("Failed generating AES key [%s]", err) - } - msg, err := GetRandomBytes(int(len.Int64()) + 1) - if err != nil { - t.Fatalf("Failed generating AES key [%s]", err) - } - - out1 := HMACAESTruncated(key, msg) - out2 := HMACTruncated(key, msg, AESKeyLength) - out3 := HMAC(key, msg) - - if !reflect.DeepEqual(out1, out2) { - t.Fatalf("Wrong hmac output [%x][%x]", out1, out2) - } - if !reflect.DeepEqual(out2, out3[:AESKeyLength]) { - t.Fatalf("Wrong hmac output [%x][%x]", out1, out2) - } - - } - -} - -func TestX509(t *testing.T) { - - // Generate a self signed cert - der, key, err := NewSelfSignedCert() - if err != nil { - t.Fatalf("Failed genereting self signed cert") - } - - // Test DERCertToPEM - pem := DERCertToPEM(der) - certFromPEM, derFromPem, err := PEMtoCertificateAndDER(pem) - if err != nil { - t.Fatalf("Failed converting PEM to (x509, DER) [%s]", err) - } - if !reflect.DeepEqual(certFromPEM.Raw, der) { - t.Fatalf("Invalid der from PEM [%x][%x]", der, certFromPEM.Raw) - } - if !reflect.DeepEqual(der, derFromPem) { - t.Fatalf("Invalid der from PEM [%x][%x]", der, derFromPem) - } - - if err := CheckCertPKAgainstSK(certFromPEM, key); err != nil { - t.Fatalf("Failed checking cert vk against sk [%s]", err) - } - - // Test PEMtoDER - if derFromPem, err = PEMtoDER(pem); err != nil { - t.Fatalf("Failed converting PEM to (DER) [%s]", err) - } - if !reflect.DeepEqual(der, derFromPem) { - t.Fatalf("Invalid der from PEM [%x][%x]", der, derFromPem) - } - - // Test PEMtoCertificate - if certFromPEM, err = PEMtoCertificate(pem); err != nil { - t.Fatalf("Failed converting PEM to (x509) [%s]", err) - } - if !reflect.DeepEqual(certFromPEM.Raw, der) { - t.Fatalf("Invalid der from PEM [%x][%x]", der, certFromPEM.Raw) - } - if err := CheckCertPKAgainstSK(certFromPEM, key); err != nil { - t.Fatalf("Failed checking cert vk against sk [%s]", err) - } - - // Test DERToX509Certificate - if certFromPEM, err = DERToX509Certificate(der); err != nil { - t.Fatalf("Failed converting DER to (x509) [%s]", err) - } - if !reflect.DeepEqual(certFromPEM.Raw, der) { - t.Fatalf("Invalid x509 from PEM [%x][%x]", der, certFromPEM.Raw) - } - if err := CheckCertPKAgainstSK(certFromPEM, key); err != nil { - t.Fatalf("Failed checking cert vk against sk [%s]", err) - } - - // Test errors - if _, err = DERToX509Certificate(pem); err == nil { - t.Fatalf("Converting DER to (x509) should fail on PEM [%s]", err) - } - - if _, err = PEMtoCertificate(der); err == nil { - t.Fatalf("Converting PEM to (x509) should fail on DER [%s]", err) - } - - certFromPEM.PublicKey = nil - if err := CheckCertPKAgainstSK(certFromPEM, key); err == nil { - t.Fatalf("Checking cert vk against sk shoud failed. Invalid VK [%s]", err) - } -} diff --git a/core/crypto/primitives/rsa.go b/core/crypto/primitives/rsa.go deleted file mode 100644 index 13ede6f4e6e..00000000000 --- a/core/crypto/primitives/rsa.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -package primitives - -import ( - "crypto/rand" - "crypto/rsa" -) - -var ( - defaultRSABitSize int -) - -// GetRSABitLength returns the RSA modulo bit size -func GetRSABitSize() int { - return defaultRSABitSize -} - -// NewRSAKey generates a new RSA Key -func NewRSAKey() (*rsa.PrivateKey, error) { - return rsa.GenerateKey(rand.Reader, defaultRSABitSize) -} diff --git a/core/crypto/primitives/x509.go b/core/crypto/primitives/x509.go index 977ad913f38..6beb32e1cee 100644 --- a/core/crypto/primitives/x509.go +++ b/core/crypto/primitives/x509.go @@ -17,13 +17,10 @@ limitations under the License. package primitives import ( - "crypto/ecdsa" "crypto/rand" - "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" - "encoding/pem" "errors" "math/big" "net" @@ -53,68 +50,6 @@ func DERToX509Certificate(asn1Data []byte) (*x509.Certificate, error) { return x509.ParseCertificate(asn1Data) } -// PEMtoCertificate converts pem to x509 -func PEMtoCertificate(raw []byte) (*x509.Certificate, error) { - block, _ := pem.Decode(raw) - if block == nil { - return nil, errors.New("No PEM block available") - } - - if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { - return nil, errors.New("Not a valid CERTIFICATE PEM block") - } - - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, err - } - - return cert, nil -} - -// PEMtoDER converts pem to der -func PEMtoDER(raw []byte) ([]byte, error) { - block, _ := pem.Decode(raw) - if block == nil { - return nil, errors.New("No PEM block available") - } - - if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { - return nil, errors.New("Not a valid CERTIFICATE PEM block") - } - - return block.Bytes, nil -} - -// PEMtoCertificateAndDER converts pem to x509 and der -func PEMtoCertificateAndDER(raw []byte) (*x509.Certificate, []byte, error) { - block, _ := pem.Decode(raw) - if block == nil { - return nil, nil, errors.New("No PEM block available") - } - - if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { - return nil, nil, errors.New("Not a valid CERTIFICATE PEM block") - } - - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, nil, err - } - - return cert, block.Bytes, nil -} - -// DERCertToPEM converts der to pem -func DERCertToPEM(der []byte) []byte { - return pem.EncodeToMemory( - &pem.Block{ - Type: "CERTIFICATE", - Bytes: der, - }, - ) -} - // GetCriticalExtension returns a requested critical extension. It also remove it from the list // of unhandled critical extensions func GetCriticalExtension(cert *x509.Certificate, oid asn1.ObjectIdentifier) ([]byte, error) { @@ -205,53 +140,3 @@ func NewSelfSignedCert() ([]byte, interface{}, error) { return cert, privKey, nil } - -// CheckCertPKAgainstSK checks certificate's publickey against the passed secret key -func CheckCertPKAgainstSK(x509Cert *x509.Certificate, privateKey interface{}) error { - switch pub := x509Cert.PublicKey.(type) { - case *rsa.PublicKey: - priv, ok := privateKey.(*rsa.PrivateKey) - if !ok { - return errors.New("Private key type does not match public key type") - } - if pub.N.Cmp(priv.N) != 0 { - return errors.New("Private key does not match public key") - } - case *ecdsa.PublicKey: - priv, ok := privateKey.(*ecdsa.PrivateKey) - if !ok { - return errors.New("Private key type does not match public key type") - - } - if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 { - return errors.New("Private key does not match public key") - } - default: - return errors.New("Unknown public key algorithm") - } - - return nil -} - -// CheckCertAgainRoot check the validity of the passed certificate against the passed certPool -func CheckCertAgainRoot(x509Cert *x509.Certificate, certPool *x509.CertPool) ([][]*x509.Certificate, error) { - opts := x509.VerifyOptions{ - // TODO DNSName: "test.example.com", - Roots: certPool, - } - - return x509Cert.Verify(opts) -} - -// CheckCertAgainstSKAndRoot checks the passed certificate against the passed secretkey and certPool -func CheckCertAgainstSKAndRoot(x509Cert *x509.Certificate, privateKey interface{}, certPool *x509.CertPool) error { - if err := CheckCertPKAgainstSK(x509Cert, privateKey); err != nil { - return err - } - - if _, err := CheckCertAgainRoot(x509Cert, certPool); err != nil { - return err - } - - return nil -} diff --git a/core/crypto/utils/conf.go b/core/crypto/utils/conf.go deleted file mode 100644 index 00afec0a160..00000000000 --- a/core/crypto/utils/conf.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package utils - -import ( - "fmt" - - "github.com/spf13/viper" -) - -// NodeConfiguration used for testing -type NodeConfiguration struct { - Type string - Name string -} - -// GetEnrollmentID returns the enrollment ID -func (conf *NodeConfiguration) GetEnrollmentID() string { - key := "tests.crypto.users." + conf.Name + ".enrollid" - value := viper.GetString(key) - if value == "" { - panic(fmt.Errorf("Enrollment id not specified in configuration file. Please check that property '%s' is set", key)) - } - return value -} - -// GetEnrollmentPWD returns the enrollment PWD -func (conf *NodeConfiguration) GetEnrollmentPWD() string { - key := "tests.crypto.users." + conf.Name + ".enrollpw" - value := viper.GetString(key) - if value == "" { - panic(fmt.Errorf("Enrollment id not specified in configuration file. Please check that property '%s' is set", key)) - } - return value -} diff --git a/core/crypto/utils/errs.go b/core/crypto/utils/errs.go deleted file mode 100644 index 2e405f332f3..00000000000 --- a/core/crypto/utils/errs.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package utils - -import "errors" - -var ( - // ErrRegistrationRequired Registration to the Membership Service required. - ErrRegistrationRequired = errors.New("Registration to the Membership Service required.") - - // ErrNotInitialized Initialization required - ErrNotInitialized = errors.New("Initialization required.") - - // ErrAlreadyInitialized Already initialized - ErrAlreadyInitialized = errors.New("Already initialized.") - - // ErrAlreadyRegistered Already registered - ErrAlreadyRegistered = errors.New("Already registered.") - - // ErrTransactionMissingCert Transaction missing certificate or signature - ErrTransactionMissingCert = errors.New("Transaction missing certificate or signature.") - - // ErrInvalidTransactionSignature Invalid Transaction Signature - ErrInvalidTransactionSignature = errors.New("Invalid Transaction Signature.") - - // ErrTransactionCertificate Missing Transaction Certificate - ErrTransactionCertificate = errors.New("Missing Transaction Certificate.") - - // ErrTransactionSignature Missing Transaction Signature - ErrTransactionSignature = errors.New("Missing Transaction Signature.") - - // ErrInvalidSignature Invalid Signature - ErrInvalidSignature = errors.New("Invalid Signature.") - - // ErrInvalidKey Invalid key - ErrInvalidKey = errors.New("Invalid key.") - - // ErrInvalidReference Invalid reference - ErrInvalidReference = errors.New("Invalid reference.") - - // ErrNilArgument Invalid reference - ErrNilArgument = errors.New("Nil argument.") - - // ErrNotImplemented Not implemented - ErrNotImplemented = errors.New("Not implemented.") - - // ErrKeyStoreAlreadyInitialized Keystore already Initilized - ErrKeyStoreAlreadyInitialized = errors.New("Keystore already Initilized.") - - // ErrEncrypt Encryption failed - ErrEncrypt = errors.New("Encryption failed.") - - // ErrDecrypt Decryption failed - ErrDecrypt = errors.New("Decryption failed.") - - // ErrDifferentChaincodeID ChaincodeIDs are different - ErrDifferentChaincodeID = errors.New("ChaincodeIDs are different.") - - // ErrDifferrentConfidentialityProtocolVersion different confidentiality protocol versions - ErrDifferrentConfidentialityProtocolVersion = errors.New("Confidentiality protocol versions are different.") - - // ErrInvalidConfidentialityLevel Invalid confidentiality level - ErrInvalidConfidentialityLevel = errors.New("Invalid confidentiality level") - - // ErrInvalidConfidentialityProtocol Invalid confidentiality level - ErrInvalidConfidentialityProtocol = errors.New("Invalid confidentiality protocol") - - // ErrInvalidTransactionType Invalid transaction type - ErrInvalidTransactionType = errors.New("Invalid transaction type") - - // ErrInvalidProtocolVersion Invalid protocol version - ErrInvalidProtocolVersion = errors.New("Invalid protocol version") -) - -// ErrToString converts and error to a string. If the error is nil, it returns the string "" -func ErrToString(err error) string { - if err != nil { - return err.Error() - } - - return "" -} diff --git a/core/crypto/utils/io.go b/core/crypto/utils/io.go index f7c042f50b4..0b4e1df95c9 100644 --- a/core/crypto/utils/io.go +++ b/core/crypto/utils/io.go @@ -16,88 +16,6 @@ limitations under the License. package utils -import ( - "encoding/base64" - "io" - "os" - "path/filepath" -) - -// DirMissingOrEmpty checks is a directory is missin or empty -func DirMissingOrEmpty(path string) (bool, error) { - dirExists, err := DirExists(path) - if err != nil { - return false, err - } - if !dirExists { - return true, nil - } - - dirEmpty, err := DirEmpty(path) - if err != nil { - return false, err - } - if dirEmpty { - return true, nil - } - return false, nil -} - -// DirExists checks if a directory exists -func DirExists(path string) (bool, error) { - _, err := os.Stat(path) - if err == nil { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return false, err -} - -// DirEmpty checks if a directory is empty -func DirEmpty(path string) (bool, error) { - f, err := os.Open(path) - if err != nil { - return false, err - } - defer f.Close() - - _, err = f.Readdir(1) - if err == io.EOF { - return true, nil - } - return false, err -} - -// FileMissing checks if a file is missing -func FileMissing(path string, name string) (bool, error) { - _, err := os.Stat(filepath.Join(path, name)) - if err != nil { - return true, err - } - return false, nil -} - -// FilePathMissing returns true if the path is missing, false otherwise. -func FilePathMissing(path string) (bool, error) { - _, err := os.Stat(path) - if err != nil { - return true, err - } - return false, nil -} - -// DecodeBase64 decodes from Base64 -func DecodeBase64(in string) ([]byte, error) { - return base64.StdEncoding.DecodeString(in) -} - -// EncodeBase64 encodes to Base64 -func EncodeBase64(in []byte) string { - return base64.StdEncoding.EncodeToString(in) -} - // IntArrayEquals checks if the arrays of ints are the same func IntArrayEquals(a []int, b []int) bool { if len(a) != len(b) { diff --git a/core/crypto/utils/slice.go b/core/crypto/utils/slice.go deleted file mode 100644 index 59e5374c386..00000000000 --- a/core/crypto/utils/slice.go +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package utils - -// Clone clones the passed slice -func Clone(src []byte) []byte { - clone := make([]byte, len(src)) - copy(clone, src) - - return clone -}