//Hardcoding this test code for PSS-SHA1
void RsaPssVerification(unsigned int uKeySize, const unsigned char* pMsg, const unsigned char* pSign,
                       unsigned int E, const unsigned char* pN, const unsigned char* pD)
{
    RSA* pRsaKey = NULL;
    const unsigned char* pDigest = NULL;
    size_t uDigestLen = 20;
    unsigned char EM[512];
    unsigned char signature[512];
    unsigned int uLen = 0;
    int status = 0;

    // Generate an RSA key pair
    pRsaKey = GetRsaKey(E, pN, pD);
    if (pRsaKey) {
        //Use the already hashed input message and compute the PSS padded data with max salt size
        pDigest = pMsg;
        printbin("HASH", pDigest, 20);
        status = RSA_padding_add_PKCS1_PSS(pRsaKey, EM, pDigest, EVP_sha1(), -2);
        printbin("EM", EM, uKeySize);
        if (status == 1)  {
            //Now do Rsa Signature (RSA private encrypt)
            status = RSA_private_encrypt(uKeySize, EM, signature, pRsaKey, RSA_NO_PADDING);
            printbin("Sign", signature, uKeySize);
            if (status != -1) {
                //Now its time to verify the signature using RSA public decryption
                //We could directly use signature, but we are here to verify the signature generated by HW KM1
                uLen = hex2bin(signature, pSign);
                //assert(uLen == uKeySize)
                printbin("Sign", signature, uLen);
                status = RSA_public_decrypt(uKeySize, signature, EM, pRsaKey, RSA_NO_PADDING);
                printbin("EM", EM, uKeySize);
                if (status != -1) {
                    //Verify the data against the message with expecting max salt length from ssignature
                    status = RSA_verify_PKCS1_PSS(pRsaKey, pDigest, EVP_sha1(), EM, -2);
                    if (status == 1) {
                        printf("GREAT: Signature verification successful\n");
                    } else {
                        printf("RSA_verify_PKCS1_PSS failed with error %s\n", ERR_error_string(ERR_get_error(), NULL));
                    }
                } else {
                    printf("RSA_public_decrypt failed with error %s\n", ERR_error_string(ERR_get_error(), NULL));
                }
            } else {
                printf("RSA_private_encrypt failed with error %s\n", ERR_error_string(ERR_get_error(), NULL));
            }
        } else {
            printf("RSA_padding_add_PKCS1_PSS failed with error %s\n", ERR_error_string(ERR_get_error(), NULL));
        }
    }

    if (pRsaKey) {
        RSA_free(pRsaKey);
    }
}
Example #2
0
static int
pkey_rsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
              const unsigned char *tbs, size_t tbslen)
{
    int ret;
    RSA_PKEY_CTX *rctx = ctx->data;
    RSA *rsa = ctx->pkey->pkey.rsa;

    if (rctx->md) {
        if (tbslen != (size_t)EVP_MD_size(rctx->md)) {
            RSAerr(RSA_F_PKEY_RSA_SIGN,
                   RSA_R_INVALID_DIGEST_LENGTH);
            return -1;
        }

        if (EVP_MD_type(rctx->md) == NID_mdc2) {
            unsigned int sltmp;

            if (rctx->pad_mode != RSA_PKCS1_PADDING)
                return -1;
            ret = RSA_sign_ASN1_OCTET_STRING(NID_mdc2, tbs, tbslen,
                                             sig, &sltmp, rsa);

            if (ret <= 0)
                return ret;
            ret = sltmp;
        } else if (rctx->pad_mode == RSA_X931_PADDING) {
            if (!setup_tbuf(rctx, ctx))
                return -1;
            memcpy(rctx->tbuf, tbs, tbslen);
            rctx->tbuf[tbslen] =
                RSA_X931_hash_id(EVP_MD_type(rctx->md));
            ret = RSA_private_encrypt(tbslen + 1, rctx->tbuf, sig,
                                      rsa, RSA_X931_PADDING);
        } else if (rctx->pad_mode == RSA_PKCS1_PADDING) {
            unsigned int sltmp;

            ret = RSA_sign(EVP_MD_type(rctx->md), tbs, tbslen, sig,
                           &sltmp, rsa);
            if (ret <= 0)
                return ret;
            ret = sltmp;
        } else if (rctx->pad_mode == RSA_PKCS1_PSS_PADDING) {
            if (!setup_tbuf(rctx, ctx))
                return -1;
            if (!RSA_padding_add_PKCS1_PSS_mgf1(rsa, rctx->tbuf,
                                                tbs, rctx->md, rctx->mgf1md, rctx->saltlen))
                return -1;
            ret = RSA_private_encrypt(RSA_size(rsa), rctx->tbuf,
                                      sig, rsa, RSA_NO_PADDING);
        } else
            return -1;
    } else
        ret = RSA_private_encrypt(tbslen, tbs, sig, ctx->pkey->pkey.rsa,
                                  rctx->pad_mode);
    if (ret < 0)
        return ret;
    *siglen = ret;
    return 1;
}
Example #3
0
/*
 * rsa private encrypt
*/
char* rsa_encrypt_private(unsigned char*txt,int txt_len,char* public_key_str,int p_len,int* enc_len)
{
    RSA* rsa;
    int rsa_len;
    char *p_en;
    #if 1
    //public_key = rsa_key_seliaze(public_key_str);
    BIO* p_bio = BIO_new_mem_buf(public_key_str, -1);
    printf("rsa_encrypt is %p \n",p_bio);
    rsa = PEM_read_bio_RSAPrivateKey(p_bio, NULL, NULL, NULL); //PEM_read_bio_RSAPrivateKey
    if ( rsa == NULL ) {
        printf("RSA is NULL\n");
        return NULL;
    }
    #else
    FILE* file=fopen("/tmp/r_pub.key","r");
    rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL);//PEM_read_RSAPrivateKey
    #endif
    rsa_len=RSA_size(rsa);
    p_en=(unsigned char *)calloc(rsa_len+1,1);
    //printf("rsa length = %d\n",rsa_len);
    int rc=0;
    if((rc=RSA_private_encrypt(txt_len,(unsigned char *)txt,(unsigned char*)p_en,rsa,RSA_PKCS1_PADDING))<=0) {
        int e=ERR_get_error();
        printf("error code is:%s\n",ERR_error_string(e,NULL));
        return NULL;
    }
    RSA_free(rsa);
    *enc_len = rc;
    return p_en;
}
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;
}
Example #5
0
/** Generate a new certificate for our loaded or generated keys, and write it
 * to disk.  Return 0 on success, nonzero on failure. */
static int
generate_certificate(void)
{
  char buf[8192];
  time_t now = time(NULL);
  struct tm tm;
  char published[ISO_TIME_LEN+1];
  char expires[ISO_TIME_LEN+1];
  char fingerprint[FINGERPRINT_LEN+1];
  char *ident = key_to_string(identity_key);
  char *signing = key_to_string(signing_key);
  FILE *f;
  size_t signed_len;
  char digest[DIGEST_LEN];
  char signature[1024]; /* handles up to 8192-bit keys. */
  int r;

  get_fingerprint(identity_key, fingerprint);

  tor_localtime_r(&now, &tm);
  tm.tm_mon += months_lifetime;

  format_iso_time(published, now);
  format_iso_time(expires, mktime(&tm));

  tor_snprintf(buf, sizeof(buf),
               "dir-key-certificate-version 3"
               "%s%s"
               "\nfingerprint %s\n"
               "dir-key-published %s\n"
               "dir-key-expires %s\n"
               "dir-identity-key\n%s"
               "dir-signing-key\n%s"
               "dir-key-certification\n",
               address?"\ndir-address ":"", address?address:"",
               fingerprint, published, expires, ident, signing);
  tor_free(ident);
  tor_free(signing);
  signed_len = strlen(buf);
  SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest);

  r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest,
                          (unsigned char*)signature,
                          EVP_PKEY_get1_RSA(identity_key),
                          RSA_PKCS1_PADDING);
  strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf));
  signed_len = strlen(buf);
  base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
  strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));

  if (!(f = fopen(certificate_file, "w"))) {
    log_err(LD_GENERAL, "Couldn't open %s for writing: %s",
            certificate_file, strerror(errno));
    return 1;
  }

  fputs(buf, f);
  fclose(f);
  return 0;
}
Example #6
0
void RSATest()
{
    RSA *key = NULL;
    BIO *bio_sec = NULL;
    BIO *bio_pub = NULL;
    FILE *fp_sec = NULL;
    FILE *fp_pub = NULL;
    fopen_s(&fp_sec, "sec.pem", "r");
    fopen_s(&fp_pub, "pub.pem", "r");
    bio_sec = BIO_new_fp(fp_sec, BIO_CLOSE);
    bio_pub = BIO_new_fp(fp_pub, BIO_CLOSE);

    if (!bio_sec || !bio_pub) {
        printf("fucked BIO_new_file\n");
        return;
    }

    if (!PEM_read_bio_RSAPrivateKey(bio_sec, &key, NULL, "")) {
        printf("fucked PEM_read_bio_RSAPrivateKey\n");
        return;
    }

    if (!PEM_read_bio_RSAPublicKey(bio_pub, &key, NULL, "")) {
        printf("fucked PEM_read_bio_RSAPublicKey\n");
        return;
    }

    int len = RSA_size(key);
    unsigned char *buf = new unsigned char[len];
    memset(buf, 0, len);

    if (-1 == RSA_private_encrypt(strlen(RSA_TEXT), (const unsigned char *)RSA_TEXT, buf, key, RSA_PKCS1_PADDING) ) {
        printf("fucked RSA_private_encrypt\n");
        return;
    }

    OutputHexString(buf, len);
    printf("\n");


    /*
    unsigned char *buf_test = new unsigned char[len];
    memset(buf_test, 0, len);

    if (-1 == RSA_public_decrypt(len, buf, buf_test, key, RSA_PKCS1_PADDING) ) {
        printf("fucked RSA_public_decrypt\n");
        return;
    }

    OutputHexString(buf_test, strlen(RSA_TEXT));
    printf("\n");
    delete [] buf_test;
    */

    delete [] buf;
    

    BIO_free(bio_sec);

}
Example #7
0
bool	rsa::encrypt_by_private_key(const void* src, size_t src_size, void* dest, size_t dest_size, size_t* en_size)
{
	if (RSA_ == NULL || src == NULL || dest == NULL || en_size == NULL)
	{
		return false;
	}

	// 정확한 SrcSize의 최대치를 구해낼 수 없다.
	// 일단 확실 한 것은 key사이즈 보다는 작다. 1024비트(128바이트)일때 117바이트라는 값이 나온다.
	// encrypt를 하면 항상 max_en_size_가 된다.
	if (src_size > max_en_size_ || dest_size < max_en_size_)
	{
		return false;
	}

	const unsigned char* in = static_cast< const unsigned char* >(src);
	unsigned char* out = static_cast< unsigned char* >(dest);

	int en_temp = RSA_private_encrypt(static_cast< int >(src_size), in, out, RSA_, RSA_PKCS1_PADDING);
	if (en_temp <= 0)
	{
		return false;
	}

	*en_size = en_temp;
	return true;
}
Example #8
0
        void RSACipher::cipher(const std::vector<unsigned char>& src, std::vector<unsigned char>& dest, const AsymmetricKey& key, KeyCompound key_compound)
        {
            const RSAKey& rsakey = static_cast<const RSAKey&>(key);

            int len = 0;
            size_t sumlen = 0;
            size_t blen = RSA_size(rsakey.d_rsa.get()) - 11;

            size_t c = (src.size() / blen) + 1;

            dest.resize(RSA_size(rsakey.d_rsa.get()) * c);

            for (size_t offset = 0; offset < src.size(); offset += blen)
            {
                if (blen + offset > src.size())
                {
                    blen = src.size() - offset;
                }

                if (key_compound == KC_PUBLIC)
                {
                    len = RSA_public_encrypt(static_cast<int>(blen), &src[offset], &dest[sumlen], rsakey.d_rsa.get(), RSA_PKCS1_PADDING);
                }
                else
                {
                    len = RSA_private_encrypt(static_cast<int>(blen), &src[offset], &dest[sumlen], rsakey.d_rsa.get(), RSA_PKCS1_PADDING);
                }

                EXCEPTION_ASSERT_WITH_LOG(len >= 0, OpenSSLException, "RSA public encrypt failed");

                sumlen += len;
            }

            dest.resize(sumlen);
        }
Example #9
0
bool RSAipher::Encrypt(const std::string& in, std::string& out)
{
	if(!IsValid())
		return false;

	int32 nLeft = int32(in.length());
	const unsigned char* pIn = (const unsigned char *)in.c_str();

	do 
	{
		memset( m_ptr0, 0, m_nRSALen);
		memset( m_ptr1, 0, m_nRSALen);

		const int32 inLen = nLeft > m_nRSALen - RSA_PKCS1_PADDING_SIZE ? m_nRSALen - RSA_PKCS1_PADDING_SIZE : nLeft;
		memcpy( m_ptr0, pIn, inLen);
		
		int32 nRetLen = IsPubKey() ? 
			RSA_public_encrypt( inLen, m_ptr0, m_ptr1, m_pKey, RSA_PKCS1_PADDING) : 
			RSA_private_encrypt( inLen, m_ptr0, m_ptr1, m_pKey, RSA_PKCS1_PADDING);

		if( nRetLen < 0 )
			break;

		nLeft -= inLen;
		pIn += inLen;

		out += inLen;
	} while ( nLeft > 0);

	return nLeft <= 0;
}
Example #10
0
/**
   \ingroup Core_Crypto
   \brief Signs data with RSA
   \param out Where to write signature
   \param in Data to sign
   \param length Length of data
   \param srsa RSA secret key
   \param rsa RSA public key
   \return number of bytes decrypted
*/
int ops_rsa_private_encrypt(unsigned char *out,const unsigned char *in,
			    size_t length,const ops_rsa_secret_key_t *srsa,
			    const ops_rsa_public_key_t *rsa)
    {
    RSA *orsa;
    int n;

    orsa=RSA_new();
    orsa->n=rsa->n;	// XXX: do we need n?
    orsa->d=srsa->d;
    orsa->p=srsa->q;
    orsa->q=srsa->p;

    /* debug */
    orsa->e=rsa->e;
    // If this isn't set, it's very likely that the programmer hasn't
    // decrypted the secret key. RSA_check_key segfaults in that case.
    // Use ops_decrypt_secret_key_from_data() to do that.
    assert(orsa->d);
    assert(RSA_check_key(orsa) == 1);
    orsa->e=NULL;
    /* end debug */

    n=RSA_private_encrypt(length,in,out,orsa,RSA_NO_PADDING);

    orsa->n=orsa->d=orsa->p=orsa->q=NULL;
    RSA_free(orsa);

    return n;
    }
Example #11
0
int32_t psRsaEncryptPriv(psPool_t *pool, psRsaKey_t *key,
    const unsigned char *in, psSize_t inlen,
    unsigned char *out, psSize_t outlen,
    void *data)
{
    return RSA_private_encrypt(inlen, in, out, *key, RSA_PKCS1_PADDING);
}
Example #12
0
bool
signHelper (
    RSA* key,
    Slice message,
    Buffer& modulus,
    Buffer& signature)
{
    int const keySize = RSA_size(key);
    if (!checkModulusLength (keySize))
        return false;

    sha256_hasher h;
    h (message.data(), message.size());
    auto digest = static_cast<sha256_hasher::result_type>(h);

    Buffer buf;

    // Pad the result (-1 -> use hash length as salt length)
    if (!RSA_padding_add_PKCS1_PSS(key,
            buf.alloc(keySize), digest.data(),
            EVP_sha256(), -1))
        return false;

    // Sign - we've manually padded the input already.
    auto ret = RSA_private_encrypt(keySize, buf.data(),
        signature.alloc (buf.size()), key, RSA_NO_PADDING);

    if (ret == -1)
        return false;

    BN_bn2bin (key->n, modulus.alloc(BN_num_bytes (key->n)));
    return true;
}
Example #13
0
QString AuthorizationManager::GenerateEncString_bridge(QString str){
  //Get the private key
  QFile keyfile("/usr/local/etc/sysadm/ws_bridge.key");
    keyfile.open(QIODevice::ReadOnly);
  QSslKey key(&keyfile, QSsl::Rsa);
  QByteArray privkey = key.toPem();
  keyfile.close();

  //Now use this private key to encode the given string
  unsigned char encode[4098] = {};
  RSA *rsa= NULL;
  BIO *keybio = NULL;
  keybio = BIO_new_mem_buf(privkey.data(), -1);
  if(keybio==NULL){ return ""; }
  rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa,NULL, NULL);
  if(rsa==NULL){ return ""; }
  int len = RSA_private_encrypt(str.length(), (unsigned char*)(str.toLatin1().data()), encode, rsa, RSA_PKCS1_PADDING);
  if(len <0){ return ""; }
  else{ 
    //Now return this as a base64 encoded string
    QByteArray str_encode( (char*)(encode), len);
    /*qDebug() << "Encoded String Info";
    qDebug() << " - Raw string:" << str << "Length:" << str.length();
    qDebug() << " - Encoded string:" << str_encode << "Length:" << str_encode.length();*/
    str_encode = str_encode.toBase64();
    /*qDebug() << " - Enc string (base64):" << str_encode << "Length:" << str_encode.length();
    qDebug() << " - Enc string (QString):" << QString(str_encode);*/
    return QString( str_encode ); 
  }

}
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;
}
void Encode_RSA(unsigned char *in,int fd)
{
	RSA *r;
	BIGNUM *bne,*bnn,*bnd;
	int bits = 1024, ret, len, flen, padding, i;
	unsigned char *key, *p;
	BIO *b;
	unsigned  char *encData,*decData,*tmpData;//加密后的数据/解密后的数据/临时指针
       /* Key data */
	unsigned long e = 75011;  

	/* 构建RSA数据结构   */
	bne = BN_new();  
	bnd = BN_new();  
	bnn = BN_new();  
	ret = BN_set_word(bne, e);  
	BN_hex2bn(&bnd, PRIVATE);  
	BN_hex2bn(&bnn, MODULUS);  

	r = RSA_new();  
	r->e=bne;  
	r->d=bnd;  
	r->n=bnn;
	/* Debug output key */
	/*RSA_print_fp(stdout, r, 5);*/

	/*准备输出的加密数据结构   */
	flen =  RSA_size(r);// - 11;   
	encData =  (unsigned char *)malloc(flen);  
	bzero(encData, flen);//memset(encData, 0, flen);   

	ret =  RSA_private_encrypt(flen, in, encData, r,  RSA_NO_PADDING);  
	if(ret < 0){
		JCG("Encrypt failed!\n");  
		return;  
	}  

	write(fd,encData,flen);

	tmpData=encData;  
#if 0
	for  (i=0; i<ret; i++)
	{
		JDG("0x%02x, ", *tmpData);
		if(i%16 == 7)
			JDG("\t");
		else if(i%16 == 15)
			JDG("\n");
		tmpData++;  
	}
	JDG("\n");

	JCG("end private encrypt ");
#endif

	free(encData);  
	RSA_free(r);  
}
Example #16
0
int Encrypt(int flen, const uint8_t* from, uint8_t* to) {
	if (!rsa)
		return -1;
	
	if (ispub)
		return RSA_public_encrypt(flen, from, to, rsa, RSA_PKCS1_PADDING);
	
	return RSA_private_encrypt(flen, from, to, rsa, RSA_PKCS1_PADDING);
}
Example #17
0
 int encrypt(int flen, unsigned char* from, unsigned char* to, rsa_padding padding) {
     assert(from && to);
     int pad = this->rsa_padding2int(padding);
     if (this->is_pub) {
         return RSA_public_encrypt(flen, from, to, this->rsa_handle.get(), pad);
     }
     else {
         return RSA_private_encrypt(flen, from, to, this->rsa_handle.get(), pad);
     }
 }
Example #18
0
extern "C" int32_t CryptoNative_RsaSignPrimitive(int32_t flen, const uint8_t* from, uint8_t* to, RSA* rsa)
{
    if (HasNoPrivateKey(rsa))
    {
        ERR_PUT_error(ERR_LIB_RSA, RSA_F_RSA_PRIVATE_ENCRYPT, RSA_R_VALUE_MISSING, __FILE__, __LINE__);
        return -1;
    }

    return RSA_private_encrypt(flen, from, to, rsa, RSA_NO_PADDING);
}
Example #19
0
static void
check_rsa(const unsigned char *in, size_t len, RSA *rsa, int padding)
{
    unsigned char *res, *res2;
    int keylen;

    res = malloc(RSA_size(rsa));
    if (res == NULL)
	errx(1, "res: ENOMEM");

    res2 = malloc(RSA_size(rsa));
    if (res2 == NULL)
	errx(1, "res2: ENOMEM");

    /* signing */

    keylen = RSA_private_encrypt(len, in, res, rsa, padding);
    if (keylen <= 0)
	errx(1, "failed to private encrypt: %d %d", (int)len, (int)keylen);

    if (keylen > RSA_size(rsa))
	errx(1, "keylen > RSA_size(rsa)");

    keylen = RSA_public_decrypt(keylen, res, res2, rsa, padding);
    if (keylen <= 0)
	errx(1, "failed to public decrypt: %d", (int)keylen);

    if (keylen != len)
	errx(1, "output buffer not same length: %d", (int)keylen);

    if (memcmp(res2, in, len) != 0)
	errx(1, "string not the same after decryption");

    /* encryption */

    keylen = RSA_public_encrypt(len, in, res, rsa, padding);
    if (keylen <= 0)
	errx(1, "failed to public encrypt: %d", (int)keylen);

    if (keylen > RSA_size(rsa))
	errx(1, "keylen > RSA_size(rsa)");

    keylen = RSA_private_decrypt(keylen, res, res2, rsa, padding);
    if (keylen <= 0)
	errx(1, "failed to private decrypt: %d", (int)keylen);

    if (keylen != len)
	errx(1, "output buffer not same length: %d", (int)keylen);

    if (memcmp(res2, in, len) != 0)
	errx(1, "string not the same after decryption");

    free(res);
    free(res2);
}
Example #20
0
int rsa_encrypt (const char *const private_key_name, void *input, int ilen, void **output, int *olen) {
  vkprintf (3, "rsa_encrypt (private_key_name = %s, ilen = %d)\n", private_key_name, ilen);
  int err = 0;
  RSA *privKey = NULL;
  *output = NULL;
  *olen = -1;
  FILE *f = fopen (private_key_name, "rb");
  if (f == NULL) {
    kprintf ("Couldn't open private key file: %s\n", private_key_name);
    return -1;
  }
  privKey = PEM_read_RSAPrivateKey (f, NULL, NULL, NULL);
  if (privKey == NULL) {
    kprintf ("PEM_read_RSAPrivateKey returns NULL.\n");
    err = -2;
    goto clean;
  }
  fclose (f);
  f = NULL;
  unsigned char key[32], iv[32];
  generate_aes_key (key, iv);
  const int rsa_size = RSA_size (privKey);
  *olen = 4 + rsa_size + 32 + ilen + AES_BLOCK_SIZE;
  unsigned char *b = *output = malloc (*olen);

  memcpy (b, &rsa_size, 4);
  if (!RSA_private_encrypt (32, key, b + 4, privKey, RSA_PKCS1_PADDING)) {
    kprintf ("RSA_private_encrypt fail.\n");
    err = -3;
    goto clean;
  }
  memcpy (b + 4 + rsa_size, iv, 32);
  EVP_CIPHER_CTX e;
  EVP_CIPHER_CTX_init (&e);
  EVP_EncryptInit_ex (&e, EVP_aes_256_cbc(), NULL, key, iv);
  int c_len, f_len;
  EVP_EncryptUpdate (&e, b + 4 + rsa_size + 32, &c_len, input, ilen);
  EVP_EncryptFinal_ex (&e, b + 4 + rsa_size + 32 + c_len, &f_len);
  EVP_CIPHER_CTX_cleanup (&e);
  int r = 4 + rsa_size + 32 + c_len + f_len;
  vkprintf (3, "c_len = %d, f_len = %d\n", c_len, f_len);
  assert (r <= *olen);
  *olen = r;
  clean:
  if (f != NULL) {
    fclose (f);
  }
  if (privKey) {
    RSA_free (privKey);
  }

  return err;
}
Example #21
0
jbyteArray Java_com_ecomdev_openvpn_core_NativeUtils_rsasign (JNIEnv* env, jclass, jbyteArray from, jint pkeyRef) {

	//	EVP_MD_CTX* ctx = reinterpret_cast<EVP_MD_CTX*>(ctxRef);
	EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);


	if (pkey == NULL || from == NULL) {
		jniThrowException(env, "java/lang/NullPointerException", "EVP_KEY is null");
		return NULL;
	}

	jbyte* data =  env-> GetByteArrayElements (from, NULL);
	int  datalen = env-> GetArrayLength(from);

	if(data==NULL )
		jniThrowException(env, "java/lang/NullPointerException", "data is null");

    int siglen;
	unsigned char* sigret = (unsigned char*)malloc(RSA_size(pkey->pkey.rsa));


	//int RSA_sign(int type, const unsigned char *m, unsigned int m_len,
	//           unsigned char *sigret, unsigned int *siglen, RSA *rsa);

	// adapted from s3_clnt.c
    /*	if (RSA_sign(NID_md5_sha1, (unsigned char*) data, datalen,
        sigret, &siglen, pkey->pkey.rsa) <= 0 ) */

    siglen = RSA_private_encrypt(datalen,(unsigned char*) data,sigret,pkey->pkey.rsa,RSA_PKCS1_PADDING);

    if (siglen < 0)
	{

        ERR_error_string_n(ERR_get_error(), opensslerr ,1024);
		jniThrowException(env, "java/security/InvalidKeyException", opensslerr);

		ERR_print_errors_fp(stderr);
		return NULL;


	}


	jbyteArray jb;

	jb =env->NewByteArray(siglen);

	env->SetByteArrayRegion(jb, 0, siglen, (jbyte *) sigret);
	free(sigret);
	return jb;

}
Example #22
0
 bool private_encrypt( const fc::vector<char>& key, uint32_t key_size, uint32_t pe, const fc::vector<char>& in, fc::vector<char>& out )
 {
     RSA* priv = get_priv( key,key_size/8,pe);
     int rtn = RSA_private_encrypt( in.size(), (unsigned char*)&in.front(), (unsigned char*)&out.front(), priv, RSA_PKCS1_OAEP_PADDING );
     RSA_free(priv);
     if( rtn >= 0 )
     {
         out.resize(rtn);
         return true;
     }
     out.resize(0);
     return false;;
 }
Example #23
0
 unsigned char* Rsa::ossl_encryptWithPrKey (const unsigned char *data, int dataSize, int& newSize) {
     unsigned char* encData = new unsigned char[RSA_size(keypair)];
     newSize = RSA_private_encrypt(dataSize, data, encData, keypair, RSA_PKCS1_PADDING);
     if (newSize == -1) {
         char* err = (char*) malloc(130);
         ERR_load_crypto_strings();
         ERR_error_string(ERR_get_error(), err);
         fprintf(stderr, "Error encrypting message: %s\n", err);
         free(err);
         return nullptr;
     }
     return encData;
 }
Example #24
0
gchar* rsaEncrypt(gchar *input, gint length, gint *encryptSize) {
	BIO *bio = BIO_new_mem_buf(AIRPORT_PRIVATE_KEY, -1);
	RSA *rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL);
	BIO_free(bio);

	gint size = RSA_size(rsa);
	gchar *data = g_malloc(size * sizeof(gchar));
	RSA_private_encrypt(length,(const unsigned char *)input,(unsigned char *)data, rsa, RSA_PKCS1_PADDING);

	*encryptSize = size;
	RSA_free(rsa);
	return data;
}
Example #25
0
		size_t rsa_key::private_encrypt(void* out, size_t out_len, const void* buf, size_t buf_len, int padding) const
		{
			assert(out_len >= size());

			if (out_len < size())
			{
				throw std::invalid_argument("out_len");
			}

			int result = RSA_private_encrypt(static_cast<int>(buf_len), static_cast<const unsigned char*>(buf), static_cast<unsigned char*>(out), ptr().get(), padding);

			throw_error_if_not(result >= 0);

			return result;
		}
int main() {
    const unsigned char text[] = "hello world";
    unsigned char crypt_text[1024];
    unsigned char decrypt_text[1024 - 11];
    RSA *public_key = NULL;
    RSA *private_key = NULL;
    public_key = RSA_new();
    private_key = RSA_new();
    FILE *fpub = fopen("public_key", "r");
    FILE *fpriv = fopen("private_key", "r");
    printf("text: %s\n", text);
    RSA *ret = PEM_read_RSA_PUBKEY(fpub, &public_key, NULL, NULL);
    printf("pubkey ret: %d\n", ret);
    ret = PEM_read_RSAPrivateKey(fpriv, &private_key, NULL, NULL);
    printf("prikey ret: %d\n", ret);

    //私钥加密,公钥解密
    int num = RSA_private_encrypt(sizeof(text) - 1, text, crypt_text, 
            private_key, RSA_PKCS1_PADDING);
    printf("num: %d\n", num); 
    for (int i = 0; i < num; i++) {
        printf("\\x%02x", crypt_text[i]);
    }

    printf("\ndecrypt\n");
    int decrypt_len = RSA_public_decrypt(num, crypt_text, decrypt_text,
            public_key, RSA_PKCS1_PADDING);
    if (decrypt_len < 0) printf("error: %lu\n", ERR_get_error());
    printf("decrypt_len: %d\n", decrypt_len);
    printf("decrypt text: %s\n", decrypt_text);

    //公钥加密,私钥解密
    num = RSA_public_encrypt(sizeof(text) - 1, text, crypt_text, 
            public_key, RSA_PKCS1_PADDING);
    printf("num: %d\n", num); 
    for (int i = 0; i < num; i++) {
        printf("\\x%02x", crypt_text[i]);
    }

    printf("\ndecrypt\n");
    decrypt_len = RSA_private_decrypt(RSA_size(private_key), crypt_text,
            decrypt_text, private_key, RSA_PKCS1_PADDING);
    if (decrypt_len < 0) printf("error: %lu\n", ERR_get_error());
    printf("decrypt_len: %d\n", decrypt_len);
    printf("decrypt text: %s\n", decrypt_text);

    return 0;
}
Example #27
0
    bytes private_key::encrypt( const bytes& in )const
    {
       if( !my ) FC_THROW_EXCEPTION( assert_exception, "!null" );
       bytes out;
       out.resize( RSA_size(my->rsa) );
       int rtn = RSA_private_encrypt( in.size(),
                                      (unsigned char*)in.data(),
                                      (unsigned char*)out.data(),
                                      my->rsa, RSA_PKCS1_OAEP_PADDING );
       if( rtn >= 0 ) {
          out.resize(rtn);
          return out;
       }

       FC_THROW_EXCEPTION( exception, "encrypt failed" );
    }
Example #28
0
int
badge_crypt(char * dst, const char * src, int len,
			char * seedbuf, int seedlen, const badge_entry * e)

{
	const char * esrc;
	int i;
	EVP_PKEY * key;

	if (len <= seedlen)
		return 0;

	/**
 	***	Always use type 1 padding since we do not want randomization.
	**/

	RSA_padding_add_PKCS1_type_1((unsigned char *) seedbuf, e->keylen,
	    (const unsigned char *) src, seedlen);
	src += seedlen;
	len -= seedlen;
	esrc = src + len;
	i = e->keylen;
	key = (EVP_PKEY *) e->key;

	while (src < esrc) {
		if (i >= e->keylen) {
			if (e->isprivate)
				i = RSA_private_encrypt(e->keylen,
				    (unsigned char *) seedbuf,
				    (unsigned char *) seedbuf,
				    key->pkey.rsa, RSA_NO_PADDING);
			else
				i = RSA_public_encrypt(e->keylen,
				    (unsigned char *) seedbuf,
				    (unsigned char *) seedbuf,
				    key->pkey.rsa, RSA_NO_PADDING);

			i = 0;
			}

		*dst++ = *src++ ^ seedbuf[i++];
		}

	return len;
}
Example #29
0
int
RSA_check_key(const RSA *key)
{
    static const unsigned char inbuf[] = "hello, world!";
    RSA *rsa = rk_UNCONST(key);
    void *buffer;
    int ret;

    /*
     * XXX I have no clue how to implement this w/o a bignum library.
     * Well, when we have a RSA key pair, we can try to encrypt/sign
     * and then decrypt/verify.
     */

    if ((rsa->d == NULL || rsa->n == NULL) &&
	(rsa->p == NULL || rsa->q || rsa->dmp1 == NULL || rsa->dmq1 == NULL || rsa->iqmp == NULL))
	return 0;

    buffer = malloc(RSA_size(rsa));
    if (buffer == NULL)
	return 0;

    ret = RSA_private_encrypt(sizeof(inbuf), inbuf, buffer,
			     rsa, RSA_PKCS1_PADDING);
    if (ret == -1) {
	free(buffer);
	return 0;
    }

    ret = RSA_public_decrypt(ret, buffer, buffer,
			      rsa, RSA_PKCS1_PADDING);
    if (ret == -1) {
	free(buffer);
	return 0;
    }

    if (ret == sizeof(inbuf) && ct_memcmp(buffer, inbuf, sizeof(inbuf)) == 0) {
	free(buffer);
	return 1;
    }
    free(buffer);
    return 0;
}
Example #30
0
// encrypt some data.
// The amount encrypted may be less than what's supplied.
// The output buffer must be at least MIN_OUT_BUFFER_SIZE.
// The output block must be decrypted in its entirety.
//
int encrypt_private(R_RSA_PRIVATE_KEY& key, DATA_BLOCK& in, DATA_BLOCK& out) {
    int n, modulus_len, retval;

    modulus_len = (key.bits+7)/8;
    n = in.len;
    if (n >= modulus_len-11) {
        n = modulus_len-11;
    }
    RSA* rp = RSA_new();
    private_to_openssl(key, rp);
    retval = RSA_private_encrypt(n, in.data, out.data, rp, RSA_PKCS1_PADDING);
    if (retval < 0) {
        RSA_free(rp);
        return ERR_CRYPTO;
    }
    out.len = RSA_size(rp);
    RSA_free(rp);
    return 0;
}