Beispiel #1
0
/** Sign the given message with an RSA key */
bool
RsaSha256::sign (
    std::string const& key,
    Slice message)
{
    // This ugly const_cast/reinterpret_cast is needed
    // on some machines. Although the documentation
    // suggests that the function accepts a void const*
    // argument, apparently some platforms have OpenSSL
    // libraries that are up-to-date but accept void*.
    auto bio = BIO_new_mem_buf(
        const_cast<void*>(static_cast<void const*>(key.data())),
        key.size());

    if (!bio)
        return false;

    detail::RsaKey rsa (PEM_read_bio_RSAPrivateKey(
        bio, NULL, NULL, NULL));

    BIO_free(bio);

    if (!rsa)
        return false;

    if (detail::signHelper (rsa.get(), message, modulus_, signature_))
        return true;

    modulus_.clear();
    signature_.clear();
    return false;
}
Beispiel #2
0
/**
 * Signs the provided digest using the private key that matches the X.509 certificate.
 *
 * @param digest digest, which is being signed.
 * @param signature memory for the signature that is created. Struct parameter <code>length</code>
 *        is set to the actual signature length.
 * @throws SignException throws exception if the signing operation failed or not enough memory
 *         allocated for the signature.
 */
void digidoc::RSASigner::sign(const Digest& digest, Signature& signature) throw(SignException)
{
    DEBUG("RSASigner::sign(digest = {type=%s,digest=%p,length=%d}, signature={signature=%p,length=%d})",
        OBJ_nid2sn(digest.type), digest.digest, digest.length, signature.signature, signature.length);

    try
    {
        // Sign the digest.
        RSACrypt rsa(privateKey);
        std::vector<unsigned char> sign = rsa.sign(digest);

        // Check that enough memory is allocated for the signature.
        if(sign.size() > signature.length)
        {
            THROW_SIGNEXCEPTION("Not enough memory for signature allocated, needs %d bytes, allocated %d bytes.",
        	        sign.size(), signature.length);
        }

        // Copy the signature to the buffer.
        memcpy(signature.signature, &sign[0], sign.size());
        signature.length = (unsigned int)sign.size();
    }
    catch(const IOException& e)
    {
        THROW_SIGNEXCEPTION_CAUSE(e, "Failed to sign digest.");
    }
}
Beispiel #3
0
int main()
{
char msg[100];
printf("enter the message to be encrypted\n");
scanf("%s",msg);
rsa(msg);
}
Beispiel #4
0
/**
 * Validate signature value.
 *
 * @throws throws exception if signature value did not match.
 */
void digidoc::SignatureBES::checkSignatureValue() const throw(SignatureException)
{
    DEBUG("SignatureBES::checkSignatureValue()");
    try
    {
        // Initialize RSA crypter.
        X509* cert = getSigningCertificate().getX509();
        X509_scope certScope(&cert);
        RSACrypt rsa(cert);

        // Calculate SHA1 digest of the Signature->SignedInfo node.
        std::auto_ptr<Digest> calc = Digest::create(NID_sha1);
        std::vector<unsigned char> sha1 = calcDigestOnNode(calc.get(), DSIG_NAMESPACE, "SignedInfo");
        DEBUGMEM("Digest", &sha1[0], sha1.size());

        // Get signature value.
        std::vector<unsigned char> signatureSha1Rsa = getSignatureValue();

        // Verify signature value with public RSA key.
        bool valid = rsa.verify(calc->getMethod(), sha1, signatureSha1Rsa);

        // Check that signature matched.
        if(!valid)
        {
            THROW_SIGNATUREEXCEPTION("Signature is not valid.");
        }
    }
    catch(const IOException& e)
    {
        THROW_SIGNATUREEXCEPTION_CAUSE(e, "Failed to validate signature.");
    }
}
Beispiel #5
0
void encrype(int e,int n){
	pre_treat();
	FILE *fp_worked;
	FILE *fp_result;
	fp_worked=Sfopen("worked.txt");
	fp_result=fopen("result.txt","w");
	
	int code,rsa_code;
	for(int i=0;i<Total_Number;i=i+configuration.BITWIDTH){
		int temp = 0;
		for(int j=0;j<configuration.BITWIDTH;j++){
			fscanf(fp_worked,"%d",&code);
			temp = temp + code * pow(10,2*(configuration.BITWIDTH-j-1));
		}
		rsa_code = rsa(temp,e,n);
		

		fprintf(fp_result,"%d\n",rsa_code);
	}
	
	fclose(fp_result);
	fclose(fp_worked);
	
	system("rm -f worked.txt"); 
}
static int sign_rsa(EVP_PKEY* pkey, keymaster_rsa_sign_params_t* sign_params, const uint8_t* data,
                    const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) {
    if (sign_params->digest_type != DIGEST_NONE) {
        ALOGW("Cannot handle digest type %d", sign_params->digest_type);
        return -1;
    } else if (sign_params->padding_type != PADDING_NONE) {
        ALOGW("Cannot handle padding type %d", sign_params->padding_type);
        return -1;
    }

    Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
    if (rsa.get() == NULL) {
        logOpenSSLError("openssl_sign_rsa");
        return -1;
    }

    UniquePtr<uint8_t, Malloc_Free> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(dataLength)));
    if (signedDataPtr.get() == NULL) {
        logOpenSSLError("openssl_sign_rsa");
        return -1;
    }

    unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get());
    if (RSA_private_encrypt(dataLength, data, tmp, rsa.get(), RSA_NO_PADDING) <= 0) {
        logOpenSSLError("openssl_sign_rsa");
        return -1;
    }

    *signedDataLength = dataLength;
    *signedData = signedDataPtr.release();

    return 0;
}
Beispiel #7
0
std::unique_ptr<RSA_PrivateKey>
make_openssl_rsa_private_key(RandomNumberGenerator& rng, size_t rsa_bits)
   {
   if (rsa_bits > INT_MAX)
      throw Internal_Error("rsa_bits overflow");

   secure_vector<uint8_t> seed(BOTAN_SYSTEM_RNG_POLL_REQUEST);
   rng.randomize(seed.data(), seed.size());
   RAND_seed(seed.data(), seed.size());

   std::unique_ptr<BIGNUM, std::function<void (BIGNUM*)>> bn(BN_new(), BN_free);
   if(!bn)
      throw OpenSSL_Error("BN_new");
   if(!BN_set_word(bn.get(), RSA_F4))
      throw OpenSSL_Error("BN_set_word");

   std::unique_ptr<RSA, std::function<void (RSA*)>> rsa(RSA_new(), RSA_free);
   if(!rsa)
      throw OpenSSL_Error("RSA_new");
   if(!RSA_generate_key_ex(rsa.get(), rsa_bits, bn.get(), nullptr))
      throw OpenSSL_Error("RSA_generate_key_ex");

   uint8_t* der = nullptr;
   int bytes = i2d_RSAPrivateKey(rsa.get(), &der);
   if(bytes < 0)
      throw OpenSSL_Error("i2d_RSAPrivateKey");

   const secure_vector<uint8_t> keydata(der, der + bytes);
   memset(der, 0, bytes);
   free(der);
   return std::unique_ptr<Botan::RSA_PrivateKey>
      (new RSA_PrivateKey(AlgorithmIdentifier(), keydata));
   }
static int generate_rsa_keypair(EVP_PKEY* pkey, const keymaster_rsa_keygen_params_t* rsa_params) {
    Unique_BIGNUM bn(BN_new());
    if (bn.get() == NULL) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    /* initialize RSA */
    Unique_RSA rsa(RSA_new());
    if (rsa.get() == NULL) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL) ||
        RSA_check_key(rsa.get()) < 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }

    if (EVP_PKEY_assign_RSA(pkey, rsa.get()) == 0) {
        logOpenSSLError("generate_rsa_keypair");
        return -1;
    }
    release_because_ownership_transferred(rsa);

    return 0;
}
static int openssl_sign_data(const keymaster_device_t* dev,
        const void* params,
        const uint8_t* keyBlob, const size_t keyBlobLength,
        const uint8_t* data, const size_t dataLength,
        uint8_t** signedData, size_t* signedDataLength) {

    int result = -1;
    EVP_MD_CTX ctx;
    size_t maxSize;

    if (data == NULL) {
        ALOGW("input data to sign == NULL");
        return -1;
    } else if (signedData == NULL || signedDataLength == NULL) {
        ALOGW("output signature buffer == NULL");
        return -1;
    }

    Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength));
    if (pkey.get() == NULL) {
        return -1;
    }

    if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) {
        ALOGW("Cannot handle non-RSA keys yet");
        return -1;
    }

    keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params;
    if (sign_params->digest_type != DIGEST_NONE) {
        ALOGW("Cannot handle digest type %d", sign_params->digest_type);
        return -1;
    } else if (sign_params->padding_type != PADDING_NONE) {
        ALOGW("Cannot handle padding type %d", sign_params->padding_type);
        return -1;
    }

    Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get()));
    if (rsa.get() == NULL) {
        logOpenSSLError("openssl_sign_data");
        return -1;
    }

    UniquePtr<uint8_t> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(dataLength)));
    if (signedDataPtr.get() == NULL) {
        logOpenSSLError("openssl_sign_data");
        return -1;
    }

    unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get());
    if (RSA_private_encrypt(dataLength, data, tmp, rsa.get(), RSA_NO_PADDING) <= 0) {
        logOpenSSLError("openssl_sign_data");
        return -1;
    }

    *signedDataLength = dataLength;
    *signedData = signedDataPtr.release();
    return 0;
}
static int openssl_generate_keypair(const keymaster_device_t* dev,
        const keymaster_keypair_t key_type, const void* key_params,
        uint8_t** keyBlob, size_t* keyBlobLength) {
    ssize_t privateLen, publicLen;

    if (key_type != TYPE_RSA) {
        ALOGW("Unsupported key type %d", key_type);
        return -1;
    } else if (key_params == NULL) {
        ALOGW("key_params == null");
        return -1;
    }

    keymaster_rsa_keygen_params_t* rsa_params = (keymaster_rsa_keygen_params_t*) key_params;

    Unique_BIGNUM bn(BN_new());
    if (bn.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    /* initialize RSA */
    Unique_RSA rsa(RSA_new());
    if (rsa.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL)
            || RSA_check_key(rsa.get()) < 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    /* assign to EVP */
    Unique_EVP_PKEY pkey(EVP_PKEY_new());
    if (pkey.get() == NULL) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }

    if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) == 0) {
        logOpenSSLError("openssl_generate_keypair");
        return -1;
    }
    OWNERSHIP_TRANSFERRED(rsa);

    if (wrap_key(pkey.get(), EVP_PKEY_RSA, keyBlob, keyBlobLength)) {
        return -1;
    }

    return 0;
}
static int openssl_verify_data(const keymaster_device_t* dev,
        const void* params,
        const uint8_t* keyBlob, const size_t keyBlobLength,
        const uint8_t* signedData, const size_t signedDataLength,
        const uint8_t* signature, const size_t signatureLength) {

    if (signedData == NULL || signature == NULL) {
        ALOGW("data or signature buffers == NULL");
        return -1;
    }

    Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength));
    if (pkey.get() == NULL) {
        return -1;
    }

    if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) {
        ALOGW("Cannot handle non-RSA keys yet");
        return -1;
    }

    keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params;
    if (sign_params->digest_type != DIGEST_NONE) {
        ALOGW("Cannot handle digest type %d", sign_params->digest_type);
        return -1;
    } else if (sign_params->padding_type != PADDING_NONE) {
        ALOGW("Cannot handle padding type %d", sign_params->padding_type);
        return -1;
    } else if (signatureLength != signedDataLength) {
        ALOGW("signed data length must be signature length");
        return -1;
    }

    Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get()));
    if (rsa.get() == NULL) {
        logOpenSSLError("openssl_verify_data");
        return -1;
    }

    UniquePtr<uint8_t> dataPtr(reinterpret_cast<uint8_t*>(malloc(signedDataLength)));
    if (dataPtr.get() == NULL) {
        logOpenSSLError("openssl_verify_data");
        return -1;
    }

    unsigned char* tmp = reinterpret_cast<unsigned char*>(dataPtr.get());
    if (!RSA_public_decrypt(signatureLength, signature, tmp, rsa.get(), RSA_NO_PADDING)) {
        logOpenSSLError("openssl_verify_data");
        return -1;
    }

    int result = 0;
    for (size_t i = 0; i < signedDataLength; i++) {
        result |= tmp[i] ^ signedData[i];
    }

    return result == 0 ? 0 : -1;
}
Beispiel #12
0
void MainWindow::on_pushGenKey_clicked()
{
	if(selectedAsymmAlgo() == Scrambler::ElGamalCypher)
	{
		if(ui->editKeySeed->text() == "")
		{
			QMessageBox::critical(this, "Ошибка", "Строка генерации не должна быть пустой.", QMessageBox::Ok);
			return;
		}

		QStringList seed = ui->editKeySeed->text().split(" ", QString::SkipEmptyParts);
		if(seed.length() < 3)
		{
			QMessageBox::critical(this, "Ошибка", "Строка генерации должна содержать три положительных целых числа.", QMessageBox::Ok);
			return;
		}

		try
		{
			Scrambler::ElGamal el(seed[0], seed[1], seed[2]);
			ui->editAsymmPubKey->setText(el.ok.toQString());
			ui->editAsymmPrivateKey->setText(el.getSecretKeyStr());
		}
		catch(Scrambler::ElGamal::Exception e)
		{
			QMessageBox::critical(this, "Ошибка", "Первое число должно быть простым.", QMessageBox::Ok);
			return;
		}
	}
	else if(selectedAsymmAlgo() == Scrambler::Rsa)
	{
		if(ui->editKeySeed->text() == "")
		{
			QMessageBox::critical(this, "Ошибка", "Строка генерации не должна быть пустой.", QMessageBox::Ok);
			return;
		}

		try
		{
			QStringList seed = ui->editKeySeed->text().split(" ", QString::SkipEmptyParts);
			if(seed.length() < 2)
			{
				QMessageBox::critical(this, "Ошибка", "Строка генерации должна содержать два положительных целых числа.", QMessageBox::Ok);
				return;
			}

			Scrambler::RSA rsa(seed[0], seed[1]);
			ui->editAsymmPrivateKey->setText(rsa.ck.toQString());
			ui->editAsymmPubKey->setText(rsa.ok.toQString());
		}
		catch(Scrambler::RSA::Exception e)
		{
			QMessageBox::critical(this, "Ошибка", "Что-то пошло не так.", QMessageBox::Ok);
			return;
		}
	}
}
Beispiel #13
0
static bool generate_keys(ScopedEVP_PKEY &private_key_out,
                          ScopedEVP_PKEY &public_key_out)
{
    ScopedEVP_PKEY private_key(EVP_PKEY_new(), EVP_PKEY_free);
    ScopedEVP_PKEY public_key(EVP_PKEY_new(), EVP_PKEY_free);
    ScopedRSA rsa(RSA_new(), RSA_free);
    ScopedBIGNUM e(BN_new(), BN_free);

    if (!private_key) {
        LOGE("Failed to allocate private key");
        openssl_log_errors();
        return false;
    }

    if (!public_key) {
        LOGE("Failed to allocate public key");
        openssl_log_errors();
        return false;
    }

    if (!rsa) {
        LOGE("Failed to allocate RSA");
        openssl_log_errors();
        return false;
    }

    if (!e) {
        LOGE("Failed to allocate BIGNUM");
        openssl_log_errors();
        return false;
    }

    BN_set_word(e.get(), RSA_F4);

    if (RSA_generate_key_ex(rsa.get(), 2048, e.get(), nullptr) < 0) {
        LOGE("RSA_generate_key_ex() failed");
        openssl_log_errors();
        return false;
    }

    if (!EVP_PKEY_assign_RSA(private_key.get(), RSAPrivateKey_dup(rsa.get()))) {
        LOGE("EVP_PKEY_assign_RSA() failed for private key");
        openssl_log_errors();
        return false;
    }

    if (!EVP_PKEY_assign_RSA(public_key.get(), RSAPublicKey_dup(rsa.get()))) {
        LOGE("EVP_PKEY_assign_RSA() failed for public key");
        openssl_log_errors();
        return false;
    }

    private_key_out = std::move(private_key);
    public_key_out = std::move(public_key);
    return true;
}
Beispiel #14
0
std::string JWA::to_pem() const {
    switch (kty()) {
        case KeyType::RSA:
            return rsa().to_pem();
        case KeyType::EC:
            return ec().to_pem();
        default:
            return std::string{};
    }
}
Beispiel #15
0
		RSAKey EVPPKey::rsaKey() const
		{
			if (type() == EVP_PKEY_RSA)
			{
				boost::shared_ptr<RSA> rsa(EVP_PKEY_get1_RSA(d_pkey.get()), RSA_free);

				return RSAKey(rsa, d_has_private_compound);
			}

			throw Exception::bad_function_call("Key type is not RSA");
		}
Beispiel #16
0
void decode(int d,int n){
	FILE *fp_result;
	FILE *fp_worked;
	int n_result,c_work;
	fp_result=fopen("result.txt","r");
	fp_worked=fopen("worked.txt","w");
	while(fscanf(fp_result,"%d",&n_result)>0){
		c_work=rsa(n_result,d,n);
		fprintf(fp_worked,"%d\n",c_work);		
	}
	fclose(fp_result);
	fclose(fp_worked);
	fp_result=NULL;
	fp_worked=NULL;
	aft_treat();
}
Beispiel #17
0
        RSAKey RSAKey::createRandom()
        {
            unsigned char data;
            if (RAND_bytes(&data, 1) != 1)
            {
                THROW_EXCEPTION_WITH_LOG(logicalaccess::LibLogicalAccessException, "Cannot retrieve cryptographically strong bytes");
            }

            RSAKey rsa(std::shared_ptr<RSA>(RSA_generate_key(1024, data | 1, NULL, NULL), RSA_free), true);

            EXCEPTION_ASSERT_WITH_LOG(rsa.d_rsa, OpenSSLException, "Cannot generate RSA key pair");

            rsa.cache();

            return rsa;
        }
Beispiel #18
0
bool
RsaSha256::validate (Slice data) const
{
    if (!ok())
        return false;

    detail::RsaKey rsa (RSA_new());

    rsa->n = BN_new();
    BN_bin2bn(modulus_.data(), modulus_.size(), rsa->n);

    rsa->e = BN_new();
    BN_set_word (rsa->e, 65537);

    return detail::validateHelper (rsa.get(), data, signature_);
}
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 #20
0
void test_rsa_mp_cert(unsigned num_stream)
{
	device_context dev_ctx;
	dev_ctx.init(10485760, num_stream);

	printf("------------------------------------------\n");
	printf("RSA1024, GPU (MP), server.key\n");
	printf("------------------------------------------\n");
	rsa_context_mp rsa("../../server.key", "anlab");
	rsa.set_device_context(&dev_ctx);
	//rsa.dump();
	if (num_stream == 0) {
		test_latency(&rsa);
		test_correctness(&rsa, 20);
	}
	else {
		for (unsigned int i = 1; i <= 16; i++)
			test_latency_stream(&rsa, &dev_ctx, i);
	}
}
Beispiel #21
0
void
CryptoKey::GetAlgorithm(JSContext* cx, JS::MutableHandle<JSObject*> aRetVal,
                        ErrorResult& aRv) const
{
  bool converted = false;
  JS::RootedValue val(cx);
  switch (mAlgorithm.mType) {
    case KeyAlgorithmProxy::AES:
      converted = ToJSValue(cx, mAlgorithm.mAes, &val);
      break;
    case KeyAlgorithmProxy::HMAC:
      converted = ToJSValue(cx, mAlgorithm.mHmac, &val);
      break;
    case KeyAlgorithmProxy::RSA: {
      RootedDictionary<RsaHashedKeyAlgorithm> rsa(cx);
      converted = mAlgorithm.mRsa.ToKeyAlgorithm(cx, rsa);
      if (converted) {
        converted = ToJSValue(cx, rsa, &val);
      }
      break;
    }
    case KeyAlgorithmProxy::EC:
      converted = ToJSValue(cx, mAlgorithm.mEc, &val);
      break;
    case KeyAlgorithmProxy::DH: {
      RootedDictionary<DhKeyAlgorithm> dh(cx);
      converted = mAlgorithm.mDh.ToKeyAlgorithm(cx, dh);
      if (converted) {
        converted = ToJSValue(cx, dh, &val);
      }
      break;
    }
  }
  if (!converted) {
    aRv.Throw(NS_ERROR_DOM_OPERATION_ERR);
    return;
  }

  aRetVal.set(&val.toObject());
}
static int verify_rsa(EVP_PKEY* pkey, keymaster_rsa_sign_params_t* sign_params,
                      const uint8_t* signedData, const size_t signedDataLength,
                      const uint8_t* signature, const size_t signatureLength) {
    if (sign_params->digest_type != DIGEST_NONE) {
        ALOGW("Cannot handle digest type %d", sign_params->digest_type);
        return -1;
    } else if (sign_params->padding_type != PADDING_NONE) {
        ALOGW("Cannot handle padding type %d", sign_params->padding_type);
        return -1;
    } else if (signatureLength != signedDataLength) {
        ALOGW("signed data length must be signature length");
        return -1;
    }

    Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
    if (rsa.get() == NULL) {
        logOpenSSLError("openssl_verify_data");
        return -1;
    }

    UniquePtr<uint8_t[]> dataPtr(new uint8_t[signedDataLength]);
    if (dataPtr.get() == NULL) {
        logOpenSSLError("openssl_verify_data");
        return -1;
    }

    unsigned char* tmp = reinterpret_cast<unsigned char*>(dataPtr.get());
    if (!RSA_public_decrypt(signatureLength, signature, tmp, rsa.get(), RSA_NO_PADDING)) {
        logOpenSSLError("openssl_verify_data");
        return -1;
    }

    int result = 0;
    for (size_t i = 0; i < signedDataLength; i++) {
        result |= tmp[i] ^ signedData[i];
    }

    return result == 0 ? 0 : -1;
}
	void SecureServer::generateRSAKey (const int& bits, const std::string& publicFilename, const std::string &privateFilename, const std::string &password) throw (boost::system::system_error) {
		const unsigned long e = RSA_F4;
		
		//Generate RSA key
		std::unique_ptr<BIGNUM,void (*)(BIGNUM*)> bignum(BN_new(), &BN_free);
		int ret;
		if((ret = BN_set_word(bignum.get(), e)) != 1){
			throw_system_error_ssl("Could not set BIGNUM word");
		}
		
		std::unique_ptr<RSA,void (*)(RSA*)> rsa(RSA_new(), &RSA_free);
		if(RSA_generate_key_ex(rsa.get(), bits, bignum.get(), nullptr) != 1){
			throw_system_error_ssl("Could not generate RSA key");
		}
		
		//Save public key
		std::unique_ptr<BIO,void (*)(BIO*)> publicBIO(BIO_new_file(publicFilename.c_str(), "w"), &BIO_free_all);
		if(!publicBIO){
			throw_system_error_ssl("Could not open "+publicFilename+" for writing");
		}
		if(PEM_write_bio_RSAPublicKey(publicBIO.get(), rsa.get()) != 1){
			throw_system_error_ssl("Could not write RSA public key");
		}
		
		//Save private key
		std::unique_ptr<BIO,void (*)(BIO*)> privateBIO(BIO_new_file(privateFilename.c_str(), "w"), &BIO_free_all);
		if(!privateBIO){
			throw_system_error_ssl("Could not open "+privateFilename+" for writing");
		}
		if(password.empty()){
			if(PEM_write_bio_RSAPrivateKey(privateBIO.get(), rsa.get(), nullptr, nullptr, 0, nullptr, nullptr) != 1){
				throw_system_error_ssl("Could not write RSA private key");
			}
		}else{
			if(PEM_write_bio_RSAPrivateKey(privateBIO.get(), rsa.get(), EVP_des_ede3_cbc(), (unsigned char *)password.data(), password.size(), nullptr, nullptr) != 1){
				throw_system_error_ssl("Could not write RSA private key");
			}
		}
	}
	void SecureServer::generateCertificate(const std::string& publicKey, const std::string& privateKey, const std::string& password,
		const long& secsValid, const std::vector<std::pair<std::string,std::string> >& x509Entries,
		const std::string& x509Filename) throw (boost::system::system_error) {
			std::cerr << "generating certificate" << std::endl;
		std::unique_ptr<X509,void (*)(X509*)> x509(X509_new(), &X509_free);
		
		if(ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), std::time(nullptr)) != 1){
			throw_system_error_ssl("Could not set X509 parameters");
		}
		X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
		X509_gmtime_adj(X509_get_notAfter(x509.get()), secsValid);
		std::unique_ptr<EVP_PKEY,void(*)(EVP_PKEY*)> privKey(EVP_PKEY_new(), &EVP_PKEY_free);
		std::unique_ptr<EVP_PKEY,void(*)(EVP_PKEY*)> pubKey(EVP_PKEY_new(), &EVP_PKEY_free);
		std::unique_ptr<BIO,void (*)(BIO*)> privateBIO(BIO_new_file(privateKey.c_str(), "r"), &BIO_free_all);
		if(!privateBIO){
			throw_system_error_ssl("Could not open "+privateKey+" for reading");
		}
		pem_password_cb* password_cb(nullptr);
		void *password_u(nullptr);
		if(!password.empty()){
			password_cb = &pemPasswordCBFromString;
			password_u = (void*)&password;
		}
		std::unique_ptr<RSA,void(*)(RSA*)> rsa(PEM_read_bio_RSAPrivateKey(privateBIO.get(), nullptr, password_cb, password_u),&RSA_free);
		if(!rsa){
			throw_system_error_ssl("Could not read PEM RSA private key from "+privateKey);
		}
		std::cerr << "read " << privateKey << std::endl;
		if(EVP_PKEY_set1_RSA(privKey.get(), rsa.get()) != 1){
			throw_system_error_ssl("Could not assign EVP_PKEY from RSA private key");
		}
		std::cerr << "assigned EVP_PKEY" << std::endl;
		std::unique_ptr<BIO,void (*)(BIO*)> publicBIO(BIO_new_file(publicKey.c_str(), "r"), &BIO_free_all);
		if(!publicBIO){
			throw_system_error_ssl("Could not open "+publicKey+" for reading");
		}
		RSA *ptr = rsa.get();
		if(PEM_read_bio_RSAPublicKey(publicBIO.get(),&ptr,nullptr,nullptr) == nullptr){
			throw_system_error_ssl("Could not read PEM RSA public key from "+publicKey);
		}
		std::cerr << "read " << publicKey << std::endl;
		if(EVP_PKEY_set1_RSA(pubKey.get(), rsa.get()) != 1){
			throw_system_error_ssl("Could not assign EVP_PKEY from RSA public key");
		}
		
		if(X509_set_pubkey(x509.get(), pubKey.get()) != 1){
			throw_system_error_ssl("Could nost assign X509 public key from EVP_PKEY");
		}
		X509_NAME *name = X509_get_subject_name(x509.get());
		std::cerr << "got subject name" << std::endl;
		for(const std::pair<std::string,std::string>& entry : x509Entries){
			if(X509_NAME_add_entry_by_txt(name, entry.first.c_str(), MBSTRING_ASC, (const unsigned char*)entry.second.c_str(), entry.second.length(), -1, 0) != 1){
				throw_system_error_ssl("Could not add X509 entry /"+entry.first+"/ = \""+entry.second+'"');
			}
			std::cerr << "added entry /" << entry.first << "/ = \"" << entry.second << '"' << std::endl;
		}
		if(X509_set_issuer_name(x509.get(),name) != 1){
			throw_system_error_ssl("Could not set X509 issuer name");
		}
		std::cerr << "set issuer name" << std::endl;
		std::unique_ptr<EVP_MD_CTX,void(*)(EVP_MD_CTX*)> mctx(EVP_MD_CTX_create(),&EVP_MD_CTX_destroy);
// 		EVP_PKEY_CTX *pkctx(nullptr);
		if(EVP_DigestSignInit(mctx.get(),nullptr,EVP_sha256(),nullptr,privKey.get()) != 1){
			throw_system_error_ssl("Could not init EVP Digest Sign");
		}
		std::cerr << "initialized EVP MD CTX" << std::endl;
		if(X509_sign_ctx(x509.get(),mctx.get()) <= 0){
			throw_system_error_ssl("Could not sign certificate");
		}
		std::cerr << "signed" << std::endl;
		std::unique_ptr<BIO,void(*)(BIO*)> x509BIO(BIO_new_file(x509Filename.c_str(),"w"),&BIO_free_all);
		if(PEM_write_bio_X509(x509BIO.get(),x509.get()) != 1){
			throw_system_error_ssl("Could not write X509 certificate");
		}
		std::cerr << "written to " << x509Filename << std::endl;
	}
static int qcom_km_get_keypair_public(const keymaster_device* dev,
        const uint8_t* keyBlob, const size_t keyBlobLength,
        uint8_t** x509_data, size_t* x509_data_length) {

    struct qcom_km_key_blob * keyblob_ptr = (struct qcom_km_key_blob *)keyBlob;

    if (x509_data == NULL || x509_data_length == NULL) {
        ALOGE("Output public key buffer == NULL");
        return -1;
    }

    if (keyBlob == NULL) {
        ALOGE("Supplied key blob was NULL");
        return -1;
    }

    // Should be large enough for keyblob data:
    if (keyBlobLength < (sizeof(qcom_km_key_blob_t))) {
        ALOGE("key blob appears to be truncated");
        return -1;
    }

    if (keyblob_ptr->magic_num != KM_MAGIC_NUM) {
        ALOGE("Cannot read key; it was not made by this keymaster");
        return -1;
    }

    if (keyblob_ptr->public_exponent_size == 0 ) {
        ALOGE("Key blob appears to have incorrect exponent length");
        return -1;
    }
    if (keyblob_ptr->modulus_size == 0 ) {
        ALOGE("Key blob appears to have incorrect modulus length");
        return -1;
    }

    Unique_RSA rsa(RSA_new());
    if (rsa.get() == NULL) {
        ALOGE("Could not allocate RSA structure");
        return -1;
    }

    rsa->n = BN_bin2bn(reinterpret_cast<const unsigned char*>(keyblob_ptr->modulus),
                               keyblob_ptr->modulus_size, NULL);
    if (rsa->n == NULL) {
       ALOGE("Failed to initialize  modulus");
        return -1;
    }

    rsa->e = BN_bin2bn(reinterpret_cast<const unsigned char*>(&keyblob_ptr->public_exponent),
                               keyblob_ptr->public_exponent_size, NULL);
    if (rsa->e == NULL) {
        ALOGE("Failed to initialize public exponent");
        return -1;
    }

    Unique_EVP_PKEY pkey(EVP_PKEY_new());
    if (pkey.get() == NULL) {
        ALOGE("Could not allocate EVP_PKEY structure");
        return -1;
    }
    if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
        ALOGE("Failed to assign rsa  parameters \n");
        return -1;
    }
    OWNERSHIP_TRANSFERRED(rsa);

    int len = i2d_PUBKEY(pkey.get(), NULL);
    if (len <= 0) {
        ALOGE("Len returned is < 0 len = %d", len);
        return -1;
    }

    UniquePtr<uint8_t> key(static_cast<uint8_t*>(malloc(len)));
    if (key.get() == NULL) {
        ALOGE("Could not allocate memory for public key data");
        return -1;
    }

    unsigned char* tmp = reinterpret_cast<unsigned char*>(key.get());
    if (i2d_PUBKEY(pkey.get(), &tmp) != len) {
        ALOGE("Len 2 returned is < 0 len = %d", len);
        return -1;
    }
    *x509_data_length = len;
    *x509_data = key.release();

    return 0;
}
Beispiel #26
0
int main(int argc, char* argv[])
{
	//char* strTestItem = NULL;
	int iTestItem = 0xFF;
	ShowTitle();

	bool bRunOneTime = false;
	for(;;)
	{
		if(1 == argc)
		{
			printf("\n\n\n");
			printf("===============================================\n\n");
			printf("1: DES   2: DES3   3: RC2   4:RC4   5:RSA   6:AES\n");
			printf("0: Exit\n");
			printf("-----------------------------------------------\n");
			printf("Please select a item to test: ");
			scanf("%d", &iTestItem);
		}
		else
		{
			bRunOneTime = true;
			if(0==lstrcmpi(argv[1], "-DES"))
				iTestItem = 1;
			else if(0==lstrcmpi(argv[1], "-DES3"))
				iTestItem = 2;
			else if(0==lstrcmpi(argv[1], "-RC2"))
				iTestItem = 3;
			else if(0==lstrcmpi(argv[1], "-RC4"))
				iTestItem = 4;
			else if(0==lstrcmpi(argv[1], "-RSA"))
				iTestItem = 5;
			else 
				iTestItem = 0;
		}

		switch(iTestItem)
		{
		case 1:
			{
				DesTest test(PKCS11_LIB_NAME);
				test.Test();
			}
			break;
		case 2:
			{
				Des3Test test(PKCS11_LIB_NAME);	
				test.Test();
			}
			break;
		case 3:
			{
				RC2Test test(PKCS11_LIB_NAME);
				test.Test();
			}
			break;
		case 4:
			{
				RC4Test test(PKCS11_LIB_NAME);
				test.Test();
			}
			break;
		case 5:
			{
				RSATest rsa(PKCS11_LIB_NAME);
				rsa.Test();
			}
			break;
		case 6:
			{
				AESTest test(PKCS11_LIB_NAME);
				test.Test();
			}
		break;
		case 0:
			return 0;
		default:
			break;
		}

		if(bRunOneTime)
			break;
	}

	printf("\n\nTest finished.\n\nPress any key to exit ...\n");
	getch();
	return 0;
}