TEST_F(KeymasterTest, ImportKeyPair_EC_Success) {
    uint8_t* key_blob;
    size_t key_blob_length;

    ASSERT_EQ(0,
            sDevice->import_keypair(sDevice, TEST_EC_KEY_1, sizeof(TEST_EC_KEY_1),
                    &key_blob, &key_blob_length))
            << "Should successfully import an EC key";
    UniqueKey key(&sDevice, key_blob, key_blob_length);

    uint8_t* x509_data;
    size_t x509_data_length;
    ASSERT_EQ(0,
            sDevice->get_keypair_public(sDevice, key_blob, key_blob_length,
                    &x509_data, &x509_data_length))
            << "Should be able to retrieve EC public key successfully";
    UniqueBlob x509_blob(x509_data, x509_data_length);

    const unsigned char *tmp = static_cast<const unsigned char*>(x509_blob.get());
    Unique_EVP_PKEY actual(d2i_PUBKEY((EVP_PKEY**) NULL, &tmp,
            static_cast<long>(x509_blob.length())));

    ASSERT_EQ(EVP_PKEY_type(actual.get()->type), EVP_PKEY_EC)
            << "Generated key type should be of type EC";

    const unsigned char *expectedTmp = static_cast<const unsigned char*>(TEST_EC_KEY_1);
    Unique_PKCS8_PRIV_KEY_INFO expectedPkcs8(
            d2i_PKCS8_PRIV_KEY_INFO((PKCS8_PRIV_KEY_INFO**) NULL, &expectedTmp,
                    sizeof(TEST_EC_KEY_1)));

    Unique_EVP_PKEY expected(EVP_PKCS82PKEY(expectedPkcs8.get()));

    ASSERT_EQ(1, EVP_PKEY_cmp(expected.get(), actual.get()))
            << "Expected and actual keys should match";
}
Beispiel #2
0
SEXP R_ecdsa_pubkey_decompose(SEXP input){
#ifndef OPENSSL_NO_EC
  const unsigned char *ptr = RAW(input);
  EVP_PKEY *pkey = d2i_PUBKEY(NULL, &ptr, LENGTH(input));
  bail(!!pkey);
  EC_KEY *ec = EVP_PKEY_get1_EC_KEY(pkey);
  const EC_POINT *pubkey = EC_KEY_get0_public_key(ec);
  const EC_GROUP *group = EC_KEY_get0_group(ec);
  int nid = EC_GROUP_get_curve_name(group);
  int keysize = nid_keysize(nid);
  BIGNUM *x = BN_new();
  BIGNUM *y = BN_new();
  BN_CTX *ctx = BN_CTX_new();
  bail(EC_POINT_get_affine_coordinates_GFp(group, pubkey, x, y, ctx));
  BN_CTX_free(ctx);
  SEXP res = PROTECT(allocVector(VECSXP, 3));
  SET_VECTOR_ELT(res, 0, mkString(my_nid2nist(nid)));
  SET_VECTOR_ELT(res, 1, bignum_to_r_size(x, keysize));
  SET_VECTOR_ELT(res, 2, bignum_to_r_size(y, keysize));
  BN_free(x);
  BN_free(y);
  EVP_PKEY_free(pkey);
  UNPROTECT(1);
  return res;
#else //OPENSSL_NO_EC
  Rf_error("OpenSSL has been configured without EC support");
#endif //OPENSSL_NO_EC
}
Beispiel #3
0
/*
 * Public key decoder.  Only supports SubjectPublicKeyInfo formated keys.
 */
static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
                                          const char *pem_header,
                                          const unsigned char *blob,
                                          size_t len, void **pctx,
                                          int *matchcount,
                                          const UI_METHOD *ui_method,
                                          void *ui_data)
{
    OSSL_STORE_INFO *store_info = NULL;
    EVP_PKEY *pkey = NULL;

    if (pem_name != NULL) {
        if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
            /* No match */
            return NULL;
        *matchcount = 1;
    }

    if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
        *matchcount = 1;
        store_info = OSSL_STORE_INFO_new_PKEY(pkey);
    }

    return store_info;
}
Beispiel #4
0
int
put_key_der(int is_public_only, PyObject *py_key_der,
            PyObject **py_private_key_ndn, PyObject **py_public_key_ndn,
            PyObject **py_public_key_digest, int *public_key_digest_len)
{
	struct ndn_pkey *key = NULL;
	const unsigned char *key_der;
	Py_ssize_t der_len;
	int r;
	unsigned long err;

	r = PyBytes_AsStringAndSize(py_key_der, (char **) &key_der, &der_len);
	JUMP_IF_NEG(r, error);

	if (is_public_only)
          key = (struct ndn_pkey*)d2i_PUBKEY(NULL, &key_der, der_len);
	else
          key = (struct ndn_pkey*)d2i_PrivateKey(EVP_PKEY_RSA, NULL, &key_der, der_len);

	r = ndn_keypair(is_public_only, key, py_private_key_ndn, py_public_key_ndn);
	JUMP_IF_NEG(r, error);

	r = create_public_key_digest(key, py_public_key_digest, public_key_digest_len);
	JUMP_IF_NEG(r, error);

	return 0;
error:
	return -1;
}
Beispiel #5
0
static isc_result_t
opensslgost_fromdns(dst_key_t *key, isc_buffer_t *data) {
	isc_region_t r;
	EVP_PKEY *pkey = NULL;
	unsigned char der[37 + 64];
	const unsigned char *p;

	isc_buffer_remainingregion(data, &r);
	if (r.length == 0)
		return (ISC_R_SUCCESS);

	if (r.length != 64)
		return (DST_R_INVALIDPUBLICKEY);
	memcpy(der, gost_prefix, 37);
	memcpy(der + 37, r.base, 64);
	isc_buffer_forward(data, 64);

	p = der;
	if (d2i_PUBKEY(&pkey, &p, (long) sizeof(der)) == NULL)
		return (dst__openssl_toresult2("d2i_PUBKEY",
					       DST_R_OPENSSLFAILURE));
	key->keydata.pkey = pkey;

	return (ISC_R_SUCCESS);
}
Beispiel #6
0
/*
 * This methods returns: 1 on Success,
 * 0 on decoding failure,
 * -1 on internal (malloc) failure, or invalid parameter if any.
 */
int CTLOG_new_from_base64(CTLOG **ct_log, const char *pkey_base64, const char *name)
{
    unsigned char *pkey_der = NULL;
    int pkey_der_len = ct_base64_decode(pkey_base64, &pkey_der);
    const unsigned char *p;
    EVP_PKEY *pkey = NULL;

    if (ct_log == NULL) {
        CTerr(CT_F_CTLOG_NEW_FROM_BASE64, ERR_R_PASSED_INVALID_ARGUMENT);
        return 0;
    }

    if (pkey_der_len <= 0) {
        CTerr(CT_F_CTLOG_NEW_FROM_BASE64, CT_R_LOG_CONF_INVALID_KEY);
        return 0;
    }

    p = pkey_der;
    pkey = d2i_PUBKEY(NULL, &p, pkey_der_len);
    OPENSSL_free(pkey_der);
    if (pkey == NULL) {
        CTerr(CT_F_CTLOG_NEW_FROM_BASE64, CT_R_LOG_CONF_INVALID_KEY);
        return 0;
    }

    *ct_log = CTLOG_new(pkey, name);
    if (*ct_log == NULL) {
        EVP_PKEY_free(pkey);
        return -1;
    }

    return 1;
}
Beispiel #7
0
struct ccn_pkey *
ccn_d2i_pubkey(const unsigned char *p, size_t size)
{
    const unsigned char *q = p;
    EVP_PKEY *ans;
    ans = d2i_PUBKEY(NULL, &q, size);
    return ((struct ccn_pkey *)ans);
}
Beispiel #8
0
   // helper.
   EVP_PKEY* 
   _GetPublicKey(const AnsiString &keyData)
   {
      // base64 decode the public key.
      AnsiString publicKeyData = Base64::Decode(keyData, keyData.GetLength());
      const unsigned char * publicKeyDataPointer = (const unsigned char*) publicKeyData.GetBuffer();

      EVP_PKEY *publicKey = d2i_PUBKEY(NULL, &publicKeyDataPointer, publicKeyData.GetLength());

      return publicKey;
   }
Beispiel #9
0
SEXP R_parse_der_pubkey(SEXP input){
  const unsigned char *ptr = RAW(input);
  EVP_PKEY *pkey = d2i_PUBKEY(NULL, &ptr, LENGTH(input));
  bail(!!pkey);
  unsigned char *buf = NULL;
  int len = i2d_PUBKEY(pkey, &buf);
  bail(len);
  SEXP res = allocVector(RAWSXP, len);
  memcpy(RAW(res), buf, len);
  OPENSSL_free(buf);
  return res;
}
Beispiel #10
0
/* 7.3.31 */
int SAF_GenerateKeyWithEPK(
	void *hSymmKeyObj,
	unsigned char *pucPublicKey,
	unsigned int uiPublicKeyLen,
	unsigned char *pucSymmKey,
	unsigned int *puiSymmKeyLen,
	void **phKeyHandle)
{
	int ret = SAR_UnknownErr;
	SAF_KEY *hkey = NULL;
	SAF_SYMMKEYOBJ *obj = (SAF_SYMMKEYOBJ *)hSymmKeyObj;
	const EVP_CIPHER *cipher;
	unsigned char keybuf[32];
	EVP_PKEY *pkey = NULL;
	EVP_PKEY_CTX *pkctx = NULL;
	size_t outlen;

	if (!hSymmKeyObj || !pucPublicKey || !pucSymmKey
		|| !puiSymmKeyLen || !phKeyHandle) {
		SAFerr(SAF_F_SAF_GENERATEKEYWITHEPK, ERR_R_PASSED_NULL_PARAMETER);
		return SAR_IndataErr;
	}

	if (uiPublicKeyLen <= 0 || uiPublicKeyLen > INT_MAX) {
		SAFerr(SAF_F_SAF_GENERATEKEYWITHEPK, SAF_R_INVALID_INPUT_LENGTH);
		return SAR_IndataLenErr;
	}

	outlen = (size_t)*puiSymmKeyLen;
	if (!(cipher = EVP_get_cipherbysgd(obj->uiCryptoAlgID))
		|| !RAND_bytes(keybuf, EVP_CIPHER_key_length(cipher))
		|| !(pkey = d2i_PUBKEY(NULL, (const unsigned char **)&pucPublicKey, (long)uiPublicKeyLen))
		|| !(pkctx = EVP_PKEY_CTX_new(pkey, NULL))
		|| !EVP_PKEY_encrypt_init(pkctx)
		|| !EVP_PKEY_encrypt(pkctx, pucSymmKey, &outlen, keybuf, (size_t)EVP_CIPHER_key_length(cipher))) {
		SAFerr(SAF_F_SAF_GENERATEKEYWITHEPK, SAF_R_ENCRYPT_KEY_FAILURE);
		goto end;
	}

	// init EVP_CIPHER_CTX
	if (!(hkey = OPENSSL_zalloc(sizeof(*hkey)))) {
		SAFerr(SAF_F_SAF_GENERATEKEYWITHEPK, ERR_R_MALLOC_FAILURE);
		goto end;
	}

	*puiSymmKeyLen = (unsigned int)outlen;
	ret = SAR_Ok;

end:
	EVP_PKEY_free(pkey);
	EVP_PKEY_CTX_free(pkctx);
	return ret;
}
Beispiel #11
0
int msgToRSApubKey(EVP_PKEY** pubKey, char* msg, int msglen){
	if(pubKey == NULL || msg == NULL || msglen < 1)
		return 0;

	*pubKey = EVP_PKEY_new();
	if(*pubKey == NULL){
		printf("ERR EVP_PKEY_new\n");
		return 0;
	}
	d2i_PUBKEY(pubKey, (const unsigned char**) &msg, msglen);
	return 1;

}
Beispiel #12
0
/**
 * Return if the signature and key verify with the local hash.
 *
 * PRECONDITION:
 *  - You know the signature and key are RSA.
 *
 * Example:
 * @code
 * <#example#>
 * @endcode
 */
static bool
_parcInMemoryVerifier_RSAKey_Verify(PARCInMemoryVerifier *verifier, PARCCryptoHash *localHash,
                                    PARCSignature *signatureToVerify, PARCBuffer *derEncodedKey)
{
    const uint8_t *der_bytes = parcByteArray_Array(parcBuffer_Array(derEncodedKey));

    long der_length = parcBuffer_Remaining(derEncodedKey);
    EVP_PKEY *unwrapped_key = d2i_PUBKEY(NULL, &der_bytes, der_length);

    if (unwrapped_key != NULL) {
        int success = 0;
        RSA *rsa = EVP_PKEY_get1_RSA(unwrapped_key);

        if (rsa != NULL) {
            int openssl_digest_type;

            switch (parcCryptoHash_GetDigestType(localHash)) {
                case PARC_HASH_SHA256:
                    openssl_digest_type = NID_sha256;
                    break;
                case PARC_HASH_SHA512:
                    openssl_digest_type = NID_sha512;
                    break;
                default:
                    trapUnexpectedState("Unknown digest type: %s",
                                        parcCryptoHashType_ToString(parcCryptoHash_GetDigestType(localHash)));
            }

            PARCBuffer *sigbits = parcSignature_GetSignature(signatureToVerify);
            PARCByteArray *bytearray = parcBuffer_Array(sigbits);
            unsigned signatureLength = (unsigned) parcBuffer_Remaining(sigbits);
            uint8_t *sigbuffer = parcByteArray_Array(bytearray);
            size_t signatureOffset = parcBuffer_ArrayOffset(sigbits);

            success = RSA_verify(openssl_digest_type,
                                 (unsigned char *) parcByteArray_Array(parcBuffer_Array(parcCryptoHash_GetDigest(localHash))),
                                 (unsigned) parcBuffer_Remaining(parcCryptoHash_GetDigest(localHash)),
                                 sigbuffer + signatureOffset,
                                 signatureLength,
                                 rsa);
            RSA_free(rsa);
        }
        EVP_PKEY_free(unwrapped_key);

        if (success) {
            return true;
        }
    }
    return false;
}
TEST_F(KeymasterTest, SignData_EC_Success) {
    uint8_t* key_blob;
    size_t key_blob_length;

    UniqueReadOnlyBlob testKey(TEST_SIGN_EC_KEY_1, sizeof(TEST_SIGN_EC_KEY_1));
    ASSERT_TRUE(testKey.get() != NULL);

    ASSERT_EQ(0,
            sDevice->import_keypair(sDevice, testKey.get(), testKey.length(),
                    &key_blob, &key_blob_length))
            << "Should successfully import an EC key";
    UniqueKey key(&sDevice, key_blob, key_blob_length);

    keymaster_ec_sign_params_t params = {
            .digest_type = DIGEST_NONE,
    };

    uint8_t* sig;
    size_t sig_length;

    UniqueReadOnlyBlob testData(TEST_SIGN_DATA_1, sizeof(TEST_SIGN_DATA_1));
    ASSERT_TRUE(testData.get() != NULL);

    ASSERT_EQ(0,
            sDevice->sign_data(sDevice, &params, key_blob, key_blob_length,
                    testData.get(), testData.length(),
                    &sig, &sig_length))
            << "Should sign data successfully";
    UniqueBlob sig_blob(sig, sig_length);

    uint8_t* x509_data;
    size_t x509_data_length;
    ASSERT_EQ(0,
            sDevice->get_keypair_public(sDevice, key_blob, key_blob_length,
                    &x509_data, &x509_data_length))
            << "Should be able to retrieve RSA public key successfully";
    UniqueBlob x509_blob(x509_data, x509_data_length);

    const unsigned char *tmp = static_cast<const unsigned char*>(x509_blob.get());
    Unique_EVP_PKEY expected(d2i_PUBKEY((EVP_PKEY**) NULL, &tmp,
            static_cast<long>(x509_blob.length())));

    Unique_EC_KEY ecKey(EVP_PKEY_get1_EC_KEY(expected.get()));

    ASSERT_EQ(1, ECDSA_verify(0, testData.get(), testData.length(), sig_blob.get(), sig_blob.length(), ecKey.get()))
            << "Signature should verify";
}
Beispiel #14
0
pki_key::pki_key(const pki_key *pk)
	:pki_base(pk->desc)
{
	int keylen;
	unsigned char *der_key, *p;

	ucount = pk->ucount;

	keylen = i2d_PUBKEY(pk->key, NULL);
	p = der_key = (unsigned char *)OPENSSL_malloc(keylen);
	check_oom(der_key);
	i2d_PUBKEY(pk->key, &p);
	p = der_key;
	key = d2i_PUBKEY(NULL, (const unsigned char**)&p, keylen);
	OPENSSL_free(der_key);
	pki_openssl_error();
}
static EVP_PKEY* keystore_loadkey(ENGINE* e, const char* key_id, UI_METHOD *ui_method,
        void *callback_data) {
    ALOGV("keystore_loadkey(%p, \"%s\", %p, %p)", e, key_id, ui_method, callback_data);

    Keystore_Reply reply;
    if (keystore_cmd(CommandCodes[GET_PUBKEY], &reply, 1, strlen(key_id), key_id) != NO_ERROR) {
        ALOGV("Cannot get public key for %s", key_id);
        return NULL;
    }

    const unsigned char* tmp = reinterpret_cast<const unsigned char*>(reply.get());
    Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &tmp, reply.length()));
    if (pkey.get() == NULL) {
        ALOGW("Cannot convert pubkey");
        return NULL;
    }

    switch (EVP_PKEY_type(pkey->type)) {
    case EVP_PKEY_RSA: {
        Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get()));
        if (!RSA_set_ex_data(rsa.get(), rsa_key_handle, reinterpret_cast<void*>(strdup(key_id)))) {
            ALOGW("Could not set ex_data for loaded RSA key");
            return NULL;
        }

        RSA_set_method(rsa.get(), &keystore_rsa_meth);
        RSA_blinding_off(rsa.get());

        /*
         * This should probably be an OpenSSL API, but EVP_PKEY_free calls
         * ENGINE_finish(), so we need to call ENGINE_init() here.
         */
        ENGINE_init(e);
        rsa->engine = e;
        rsa->flags |= RSA_FLAG_EXT_PKEY;

        break;
    }
    default:
        ALOGE("Unsupported key type %d", EVP_PKEY_type(pkey->type));
        return NULL;
    }

    return pkey.release();
}
Beispiel #16
0
EVP_PKEY*
sldns_ed4482pkey_raw(const unsigned char* key, size_t keylen)
{
	/* ASN1 for ED448 is 3043300506032b6571033a00 <57byteskey> */
	uint8_t pre[] = {0x30, 0x43, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65,
		0x71, 0x03, 0x3a, 0x00};
        int pre_len = 12;
	uint8_t buf[256];
        EVP_PKEY *evp_key;
	/* pp gets modified by d2i() */
        const unsigned char* pp = (unsigned char*)buf;
	if(keylen != 57 || keylen + pre_len > sizeof(buf))
		return NULL; /* wrong length */
	memmove(buf, pre, pre_len);
	memmove(buf+pre_len, key, keylen);
	evp_key = d2i_PUBKEY(NULL, &pp, (int)(pre_len+keylen));
        return evp_key;
}
void OSSLGOSTPublicKey::setQ(const ByteString& inQ)
{
	GOSTPublicKey::setQ(inQ);

	if (inQ.size() != 64)
	{
		ERROR_MSG("bad GOST public key size %zu", q.size());
		return;
	}

	ByteString der;
	der.resize(37 + 64);
	memcpy(&der[0], gost_prefix, 37);
	memcpy(&der[37], inQ.const_byte_str(), 64);
	const unsigned char *p = &der[0];
	if (d2i_PUBKEY(&pkey, &p, (long) der.size()) == NULL)
		ERROR_MSG("d2i_PUBKEY failed");
}
Beispiel #18
0
EC_KEY *d2i_EC_PUBKEY(EC_KEY **a, const unsigned char **pp, long length)
	{
	EVP_PKEY *pkey;
	EC_KEY *key;
	const unsigned char *q;
	q = *pp;
	pkey = d2i_PUBKEY(NULL, &q, length);
	if (!pkey) return(NULL);
	key = EVP_PKEY_get1_EC_KEY(pkey);
	EVP_PKEY_free(pkey);
	if (!key)  return(NULL);
	*pp = q;
	if (a)
		{
		EC_KEY_free(*a);
		*a = key;
		}
	return(key);
	}
Beispiel #19
0
EVP_PKEY *pki_evp::priv2pub(EVP_PKEY* key)
{
	int keylen;
	unsigned char *p, *p1;
	EVP_PKEY *pubkey;

	keylen = i2d_PUBKEY(key, NULL);
	p1 = p = (unsigned char *)OPENSSL_malloc(keylen);
	check_oom(p);

	/* convert rsa/dsa/ec to Pubkey */
	keylen = i2d_PUBKEY(key, &p);
	pki_openssl_error();
	p = p1;
	pubkey = d2i_PUBKEY(NULL, (const unsigned char**)&p, keylen);
	OPENSSL_free(p1);
	pki_openssl_error();
	return pubkey;
}
DSA *d2i_DSA_PUBKEY(DSA **a, unsigned char **pp,
	     long length)
{
	EVP_PKEY *pkey;
	DSA *key;
	unsigned char *q;
	q = *pp;
	pkey = d2i_PUBKEY(NULL, &q, length);
	if(!pkey) return NULL;
	key = EVP_PKEY_get1_DSA(pkey);
	EVP_PKEY_free(pkey);
	if(!key) return NULL;
	*pp = q;
	if(a) {
		DSA_free(*a);
		*a = key;
	}
	return key;
}
TEST_P(KeymasterGenerateECTest, GenerateKeyPair_EC_Success) {
    keymaster_keypair_t key_type = TYPE_EC;
    keymaster_ec_keygen_params_t params = {
            .field_size = GetParam(),
    };

    uint8_t* key_blob;
    size_t key_blob_length;

    ASSERT_EQ(0,
            sDevice->generate_keypair(sDevice, key_type, &params, &key_blob, &key_blob_length))
            << "Should generate an EC key with " << GetParam() << " field size";
    UniqueKey key(&sDevice, key_blob, key_blob_length);

    uint8_t* x509_data = NULL;
    size_t x509_data_length;
    ASSERT_EQ(0,
            sDevice->get_keypair_public(sDevice, key_blob, key_blob_length,
                    &x509_data, &x509_data_length))
            << "Should be able to retrieve EC public key successfully";
    UniqueBlob x509_blob(x509_data, x509_data_length);
    ASSERT_FALSE(x509_blob.get() == NULL)
            << "X509 data should be allocated";

    const unsigned char *tmp = static_cast<const unsigned char*>(x509_blob.get());
    Unique_EVP_PKEY actual(d2i_PUBKEY((EVP_PKEY**) NULL, &tmp,
            static_cast<long>(x509_blob.length())));

    ASSERT_EQ(EVP_PKEY_EC, EVP_PKEY_type(actual.get()->type))
            << "Generated key type should be of type EC";

    Unique_EC_KEY ecKey(EVP_PKEY_get1_EC_KEY(actual.get()));
    ASSERT_FALSE(ecKey.get() == NULL)
            << "Should be able to extract EC key from EVP_PKEY";

    ASSERT_FALSE(EC_KEY_get0_group(ecKey.get()) == NULL)
            << "EC key should have a EC_GROUP";

    ASSERT_TRUE(EC_KEY_check_key(ecKey.get()))
            << "EC key should check correctly";
}
Beispiel #22
0
EVP_PKEY*
sldns_gost2pkey_raw(unsigned char* key, size_t keylen)
{
	/* prefix header for X509 encoding */
	uint8_t asn[37] = { 0x30, 0x63, 0x30, 0x1c, 0x06, 0x06, 0x2a, 0x85, 
		0x03, 0x02, 0x02, 0x13, 0x30, 0x12, 0x06, 0x07, 0x2a, 0x85, 
		0x03, 0x02, 0x02, 0x23, 0x01, 0x06, 0x07, 0x2a, 0x85, 0x03, 
		0x02, 0x02, 0x1e, 0x01, 0x03, 0x43, 0x00, 0x04, 0x40};
	unsigned char encoded[37+64];
	const unsigned char* pp;
	if(keylen != 64) {
		/* key wrong size */
		return NULL;
	}

	/* create evp_key */
	memmove(encoded, asn, 37);
	memmove(encoded+37, key, 64);
	pp = (unsigned char*)&encoded[0];

	return d2i_PUBKEY(NULL, &pp, (int)sizeof(encoded));
}
Beispiel #23
0
static int gost_get_public_key(const knot_binary_t *dnskey_rdata, EVP_PKEY **key)
{
	assert(dnskey_rdata);
	assert(key);

	const uint8_t *pubkey_data = NULL;
	size_t pubkey_size = 0;
	if (!any_dnskey_get_pubkey(dnskey_rdata, &pubkey_data, &pubkey_size)) {
		return KNOT_EINVAL;
	}

	if (pubkey_size != GOST_DNSSEC_PUBKEY_SIZE) {
		return KNOT_DNSSEC_EINVALID_KEY;
	}

	// construct X.509 public key

	uint8_t x509_pubkey[GOST_X509_PUBKEY_SIZE] = { '\0' };
	uint8_t *prefix = x509_pubkey;
	uint8_t *keydata = x509_pubkey + GOST_X509_PUBKEY_PREFIX_SIZE;

	memcpy(prefix, gost_x509_pubkey_prefix, GOST_X509_PUBKEY_PREFIX_SIZE);
	memcpy(keydata, pubkey_data, pubkey_size);

	// construct EVP_PKEY

	const unsigned char **parse = (const unsigned char **)&prefix;
	EVP_PKEY *result = d2i_PUBKEY(NULL, parse, GOST_X509_PUBKEY_SIZE);
	if (!result) {
		return KNOT_DNSSEC_EINVALID_KEY;
	}

	*key = result;

	return KNOT_EOK;
}
Beispiel #24
0
EVP_PKEY *pki_evp::decryptKey() const
{
	unsigned char *p;
	const unsigned char *p1;
	int outl, decsize;
	unsigned char iv[EVP_MAX_IV_LENGTH];
	unsigned char ckey[EVP_MAX_KEY_LENGTH];

	EVP_PKEY *tmpkey;
	EVP_CIPHER_CTX ctx;
	const EVP_CIPHER *cipher = EVP_des_ede3_cbc();
	char ownPassBuf[MAX_PASS_LENGTH] = "";

	if (isPubKey()) {
		unsigned char *q;
		outl = i2d_PUBKEY(key, NULL);
		p = q = (unsigned char *)OPENSSL_malloc(outl);
		check_oom(q);
		i2d_PUBKEY(key, &p);
		p = q;
		tmpkey = d2i_PUBKEY(NULL, (const unsigned char**)&p, outl);
		OPENSSL_free(q);
		return tmpkey;
	}
	/* This key has its own password */
	if (ownPass == ptPrivate) {
		int ret;
		pass_info pi(XCA_TITLE, qApp->translate("MainWindow",
			"Please enter the password to decrypt the private key: '%1'").arg(getIntName()));
		ret = MainWindow::passRead(ownPassBuf, MAX_PASS_LENGTH, 0, &pi);
		if (ret < 0)
			throw errorEx(tr("Password input aborted"), class_name);
	} else if (ownPass == ptBogus) { // BOGUS pass
		ownPassBuf[0] = '\0';
	} else {
		memcpy(ownPassBuf, passwd, MAX_PASS_LENGTH);
		//printf("Orig password: '******' len:%d\n", passwd, strlen(passwd));
		while (md5passwd(ownPassBuf) != passHash &&
			sha512passwd(ownPassBuf, passHash) != passHash)
		{
			int ret;
			//printf("Passhash= '%s', new hash= '%s', passwd= '%s'\n",
				//CCHAR(passHash), CCHAR(md5passwd(ownPassBuf)), ownPassBuf);
			pass_info p(XCA_TITLE, tr("Please enter the database password for decrypting the key '%1'").arg(getIntName()));
			ret = MainWindow::passRead(ownPassBuf, MAX_PASS_LENGTH, 0, &p);
			if (ret < 0)
				throw errorEx(tr("Password input aborted"), class_name);
		}
	}
	//printf("Using decrypt Pass: %s\n", ownPassBuf);
	p = (unsigned char *)OPENSSL_malloc(encKey.count());
	check_oom(p);
	pki_openssl_error();
	p1 = p;
	memset(iv, 0, EVP_MAX_IV_LENGTH);

	memcpy(iv, encKey.constData(), 8); /* recover the iv */
	/* generate the key */
	EVP_BytesToKey(cipher, EVP_sha1(), iv, (unsigned char *)ownPassBuf,
		strlen(ownPassBuf), 1, ckey,NULL);
	/* we use sha1 as message digest,
	 * because an md5 version of the password is
	 * stored in the database...
	 */
	EVP_CIPHER_CTX_init(&ctx);
	EVP_DecryptInit(&ctx, cipher, ckey, iv);
	EVP_DecryptUpdate(&ctx, p , &outl,
		(const unsigned char*)encKey.constData() +8, encKey.count() -8);

	decsize = outl;
	EVP_DecryptFinal(&ctx, p + decsize , &outl);
	decsize += outl;
	//printf("Decrypt decsize=%d, encKey_len=%d\n", decsize, encKey_len);
	pki_openssl_error();
	tmpkey = d2i_PrivateKey(key->type, NULL, &p1, decsize);
	pki_openssl_error();
	OPENSSL_free(p);
	EVP_CIPHER_CTX_cleanup(&ctx);
	pki_openssl_error();
	if (EVP_PKEY_type(tmpkey->type) == EVP_PKEY_RSA)
		RSA_blinding_on(tmpkey->pkey.rsa, NULL);
	return tmpkey;
}
Beispiel #25
0
U8_EXPORT ssize_t u8_cryptic
(int do_encrypt,const char *cname,
 const unsigned char *key,int keylen,
 const unsigned char *iv,int ivlen,
 u8_block_reader reader,u8_block_writer writer,
 void *readstate,void *writestate,
 u8_context caller)
{
  if (strncasecmp(cname,"rsa",3)==0) {
    ENGINE *eng=ENGINE_get_default_RSA();
    EVP_PKEY _pkey, *pkey; EVP_PKEY_CTX *ctx; 
    int pubkeyin=(strncasecmp(cname,"rsapub",6)==0);
    const unsigned char *scankey=key;
    struct U8_BYTEBUF bb;
    int retval=-1;
    if (pubkeyin) pkey=d2i_PUBKEY(NULL,&scankey,keylen);
    else pkey=d2i_PrivateKey((EVP_PKEY_RSA),NULL,&scankey,keylen);
    if (!(pkey)) ctx=NULL;
    else {
#if (OPENSSL_VERSION_NUMBER>=0x1000204fL)
      ctx=EVP_PKEY_CTX_new(pkey,eng);
#else
      ctx=EVP_PKEY_CTX_new(pkey,NULL);
#endif
    }
    if (ctx) {
      memset(&bb,0,sizeof(bb));
      bb.u8_direction=u8_output_buffer;
      bb.u8_buf=bb.u8_ptr=(u8_byte *)u8_malloc(1024);
      bb.u8_lim=(u8_byte *)(bb.u8_buf+1024);
      bb.u8_growbuf=1;
      fill_bytebuf(&bb,reader,readstate);}
    if (!(ctx)) {}
    else if ((pubkeyin)?
	     ((do_encrypt)?((retval=EVP_PKEY_encrypt_init(ctx))<0):
	      ((retval=EVP_PKEY_verify_recover_init(ctx))<0)):
	     ((do_encrypt)?((retval=EVP_PKEY_sign_init(ctx))<0):
	      ((retval=EVP_PKEY_decrypt_init(ctx))<0))) {}
    else {
      unsigned char *in=bb.u8_buf; size_t inlen=bb.u8_ptr-bb.u8_buf;
      unsigned char *out=NULL; size_t outlen;
      if (pubkeyin) {
	if (do_encrypt) retval=EVP_PKEY_encrypt(ctx,NULL,&outlen,in,inlen);
	else retval=EVP_PKEY_verify_recover(ctx,NULL,&outlen,in,inlen);}
      else if (do_encrypt) retval=EVP_PKEY_sign(ctx,NULL,&outlen,in,inlen);
      else retval=EVP_PKEY_decrypt(ctx,NULL,&outlen,in,inlen);
      if (retval<0) {}
      else if ((out=u8_malloc(outlen))==NULL) {}
      else if (pubkeyin) {
	if (do_encrypt) retval=EVP_PKEY_encrypt(ctx,out,&outlen,in,inlen);
	else retval=EVP_PKEY_verify_recover(ctx,out,&outlen,in,inlen);}
      else if (do_encrypt) retval=EVP_PKEY_sign(ctx,out,&outlen,in,inlen);
      else retval=EVP_PKEY_decrypt(ctx,out,&outlen,in,inlen);
      if (retval<0) {}
      else retval=writer(out,outlen,writestate);
      if (out) u8_free(out);}
    u8_free(bb.u8_buf);
    if (retval<0) {
      unsigned long err=ERR_get_error(); char buf[512];
      buf[0]='\0'; ERR_error_string_n(err,buf,512);
      u8_seterr(u8_InternalCryptoError,OPENSSL_CRYPTIC,u8_fromlibc((char *)buf));
      ERR_clear_error();}
    if (ctx) EVP_PKEY_CTX_free(ctx);
    if (pkey)  EVP_PKEY_free(pkey);
    return retval;}
  else {
    EVP_CIPHER_CTX ctx;
    int inlen, outlen, retval=0;
    ssize_t totalout=0, totalin=0;
    unsigned char inbuf[1024], outbuf[1024+EVP_MAX_BLOCK_LENGTH];
    const EVP_CIPHER *cipher=((cname)?(EVP_get_cipherbyname(cname)):
			      (EVP_aes_128_cbc()));

    if (cipher) {
      int needkeylen=EVP_CIPHER_key_length(cipher);
      int needivlen=EVP_CIPHER_iv_length(cipher);
      int blocksize=EVP_CIPHER_block_size(cipher);
      if (blocksize>1024) blocksize=1024;
      u8_log(CRYPTO_LOGLEVEL,OPENSSL_CRYPTIC,
	     " %s cipher=%s, keylen=%d/%d, ivlen=%d/%d, blocksize=%d\n",
	     ((do_encrypt)?("encrypt"):("decrypt")),
	     cname,keylen,needkeylen,ivlen,needivlen,blocksize);

      if ((needivlen)&&(ivlen)&&(ivlen!=needivlen))
	return u8_reterr(u8_BadCryptoIV,
			 ((caller)?(caller):(OPENSSL_CRYPTIC)),
			 u8_mkstring("%d!=%d(%s)",ivlen,needivlen,cname));

      memset(&ctx,0,sizeof(ctx));

      EVP_CIPHER_CTX_init(&ctx);

      retval=EVP_CipherInit(&ctx, cipher, NULL, NULL, do_encrypt);
      if (retval==0)
	return u8_reterr(u8_CipherInit_Failed,
			 ((caller)?(caller):(OPENSSL_CRYPTIC)),
			 u8_strdup(cname));

      retval=EVP_CIPHER_CTX_set_key_length(&ctx,keylen);
      if (retval==0)
	return u8_reterr(u8_BadCryptoKey,
			 ((caller)?(caller):(OPENSSL_CRYPTIC)),
			 u8_mkstring("%d!=%d(%s)",keylen,needkeylen,cname));

      if ((needivlen)&&(ivlen!=needivlen))
	return u8_reterr(u8_BadCryptoIV,
			 ((caller)?(caller):(OPENSSL_CRYPTIC)),
			 u8_mkstring("%d!=%d(%s)",ivlen,needivlen,cname));

      retval=EVP_CipherInit(&ctx, cipher, key, iv, do_encrypt);
      if (retval==0)
	return u8_reterr(u8_CipherInit_Failed,
			 ((caller)?(caller):(OPENSSL_CRYPTIC)),
			 u8_strdup(cname));

      while (1) {
	inlen = reader(inbuf,blocksize,readstate);
	if (inlen <= 0) {
	  u8_log(CRYPTO_LOGLEVEL,OPENSSL_CRYPTIC,
		 "Finished %s(%s) with %ld in, %ld out",
		 ((do_encrypt)?("encrypt"):("decrypt")),
		 cname,totalin,totalout);
	  break;}
	else totalin=totalin+inlen;
	if (!(EVP_CipherUpdate(&ctx,outbuf,&outlen,inbuf,inlen))) {
	  char *details=u8_malloc(256);
	  unsigned long err=ERR_get_error();
	  ERR_error_string_n(err,details,256);
	  EVP_CIPHER_CTX_cleanup(&ctx);
	  return u8_reterr(u8_InternalCryptoError,
			   ((caller)?(caller):((u8_context)"u8_cryptic")),
			   details);}
	else {
	  u8_log(CRYPTO_LOGLEVEL,OPENSSL_CRYPTIC,
		 "%s(%s) consumed %d/%ld bytes, emitted %d/%ld bytes"
		 " in=<%v>\n out=<%v>",
		 ((do_encrypt)?("encrypt"):("decrypt")),cname,
		 inlen,totalin,outlen,totalout+outlen,
		 inbuf,inlen,outbuf,outlen);
	  writer(outbuf,outlen,writestate);
	  totalout=totalout+outlen;}}
      if (!(EVP_CipherFinal(&ctx,outbuf,&outlen))) {
	char *details=u8_malloc(256);
	unsigned long err=ERR_get_error();
	ERR_error_string_n(err,details,256);
	EVP_CIPHER_CTX_cleanup(&ctx);
	return u8_reterr(u8_InternalCryptoError,
			 ((caller)?(caller):(OPENSSL_CRYPTIC)),
			 details);}
      else {
	writer(outbuf,outlen,writestate);
	u8_log(CRYPTO_LOGLEVEL,OPENSSL_CRYPTIC,
	       "%s(%s) done after consuming %ld/%ld bytes, emitting %ld/%ld bytes"
	       "\n final out=<%v>",
	       ((do_encrypt)?("encrypt"):("decrypt")),cname,
	       inlen,totalin,outlen,totalout+outlen,
	       outbuf,outlen);
	EVP_CIPHER_CTX_cleanup(&ctx);
	totalout=totalout+outlen;
	return totalout;}}
    else {
      char *details=u8_malloc(256);
      unsigned long err=ERR_get_error();
      ERR_error_string_n(err,details,256);
      return u8_reterr("Unknown cipher",
		       ((caller)?(caller):((u8_context)"u8_cryptic")),
		       details);}
  }
}