OPENSSL RSA 加解密 长字符串

OPENSSL RSA 加解密 长字符串,用处,只有用到的人才会明白。

OPENSSL RSA 加解密,如果超过 密钥长度/8 ,肯定会失败,加密又不同,如果超 密钥长度/8 -11 同样会出问题;

遇到才会知道,并不是可能加密很长字符串,当然说了上面的,大家也就明白怎么做了

样例:

一、私钥加密

  RSA* utils_openssl::createRSA(unsigned char* key, int flag)
{
    RSA *rsa= NULL;
    BIO *keybio=NULL;
    keybio = BIO_new_mem_buf(key, -1);

    if (keybio==NULL) {
        LOGD( "Failed to create key BIO");
        return 0;
    }

    if(flag)
		rsa = PEM_read_bio_RSAPublicKey(keybio, NULL, NULL, NULL);
    else
        rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL);
	BIO_free_all(keybio);
    if(rsa == NULL)
        LOGD( "Failed to create RSA");

    return rsa;
}
 static unsigned char*outTmp = (unsigned char *)malloc(RSA_KEY_LENGTH / 8 - 11);
  int utils_openssl::private_encrypt_lengthStr(string privateKay, string strData, int * outlen, unsigned char** outEcrypted)
  {
	  int result = -1;
 
	  RSA * pRSAPrivateKey = createRSA((unsigned char*)privateKay.c_str(), 0);
	  //padding is the padding mode that was used to sign the data.
	  int blockSize = RSA_size(pRSAPrivateKey) - 11;
	  
	  int data_len = strData.length();
	  unsigned char* inputData = (unsigned char*)strData.c_str();
	  unsigned char*out = outTmp;// (unsigned char *)malloc(blockSize);
	  unsigned char*enc_tmp =  (unsigned char *)malloc(blockSize);
 

	  int dataLen = data_len;
	  for (int i = 0; i <= dataLen / blockSize; i++) {
		  int pos = i * blockSize;
		  if (pos == dataLen) {
			  break;
		  }

		  int length = blockSize;
		  if (pos + blockSize > dataLen) {
			  length = dataLen - pos;
		  }
		  memset((void *)out, 0, blockSize);
		  memset((void *)enc_tmp, 0, blockSize);

		  memcpy(enc_tmp, inputData + pos, length);
		  result = RSA_private_encrypt(length, enc_tmp, out, pRSAPrivateKey, THIS_RSA_PADDING);

		  if (result>0 && nullptr != out)
		  {
			  memcpy((*outEcrypted) + i*result, out, result);
			  (*outlen) += result;
		  }
		  else
		  {
			  LOGD("RSA_public_decrypt failed/n");
			  int errorcode = ERR_get_error();
			  //加载错误信息
			  //  int loaderr =   ERR_load_ERR_strings();
			  ERR_load_crypto_strings();
			  // 获取错误号
			  unsigned long ulErr = ERR_get_error();
			  char szErrMsg[1024] = { 0 };
			  char *pTmp = NULL;
			  // 格式:error:errId:库:函数:原因
			  pTmp = ERR_error_string(ulErr, szErrMsg);
			  LOGE("rsa error string:%s/n", pTmp);
			  //ERR_error_string_n();
			  break;
		  }
	  }
	  RSA_free(pRSAPrivateKey);
//	  free(out);
	  free(enc_tmp);
	  return result;
  }

二、公钥解密:

//公钥解密
  string utils_openssl::public_decrypt(unsigned char* enc_data, int data_len, unsigned char* key )
{
    RSA * rsa = createRSA(key, 1);
    int decryptLen = RSA_size(rsa);
    unsigned char*out =  (unsigned char *)malloc(decryptLen);
    unsigned char*enc_tmp =  (unsigned char *)malloc(decryptLen);
    if(NULL == out)
    {
        LOGD("pubkey_decrypt:malloc error!");
        return "";
    }
    string deContent="";
    int dataLen = data_len;
    for (int i = 0; i <= dataLen / decryptLen; i++) {
        int pos = i * decryptLen;
        if (pos == dataLen) {
            break;
        }
        int length = decryptLen;
        if (pos + decryptLen > dataLen) {
            length = dataLen - pos;
        }
        memset((void *)out, 0, decryptLen);
        memset((void *)enc_tmp, 0, decryptLen);

        memcpy(enc_tmp, enc_data+pos, length);
		int  result = RSA_public_decrypt(length, enc_tmp, out, rsa, THIS_RSA_PADDING);

        if(result>0)
        {
            deContent+=(char*)out;
        } else
        {
            LOGD("RSA_public_decrypt failed/n");
            int errorcode = ERR_get_error();
            //加载错误信息
          //  int loaderr =   ERR_load_ERR_strings();
            ERR_load_crypto_strings();
            // 获取错误号
            unsigned long ulErr = ERR_get_error();
            char szErrMsg[1024] = {0};
            char *pTmp = NULL;
            // 格式:error:errId:库:函数:原因
            pTmp = ERR_error_string(ulErr,szErrMsg);
            LOGE("rsa error string:%s/n",pTmp);
            //ERR_error_string_n();
			deContent = "";
            break;
        }
    }
    RSA_free(rsa);
	CRYPTO_cleanup_all_ex_data();
    free(out);
    free(enc_tmp);
    return deContent;
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是使用 OpenSSL 库编写 RSA 加解密算法的示例代码,你可以根据自己的需求进行修改: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/rsa.h> #include <openssl/pem.h> int main(int argc, char* argv[]) { // 生成 RSA 密钥对 RSA* rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL); if (rsa == NULL) { printf("RSA_generate_key failed!\n"); return -1; } // 保存公钥和私钥到文件中 FILE* fp = fopen("public_key.pem", "w"); if (fp == NULL) { printf("Open public_key.pem failed!\n"); return -1; } PEM_write_RSAPublicKey(fp, rsa); fclose(fp); fp = fopen("private_key.pem", "w"); if (fp == NULL) { printf("Open private_key.pem failed!\n"); return -1; } PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL); fclose(fp); // 加密字符串 const char* plain_text = "Hello, RSA!"; int plain_text_len = strlen(plain_text); int max_cipher_len = RSA_size(rsa); unsigned char* cipher_text = (unsigned char*)malloc(max_cipher_len); int cipher_len = RSA_public_encrypt(plain_text_len, (const unsigned char*)plain_text, cipher_text, rsa, RSA_PKCS1_PADDING); if (cipher_len < 0) { printf("RSA_public_encrypt failed!\n"); return -1; } // 解密字符串 unsigned char* result = (unsigned char*)malloc(plain_text_len + 1); int result_len = RSA_private_decrypt(cipher_len, cipher_text, result, rsa, RSA_PKCS1_PADDING); if (result_len < 0) { printf("RSA_private_decrypt failed!\n"); return -1; } result[result_len] = '\0'; printf("plain_text: %s\n", plain_text); printf("cipher_len: %d\n", cipher_len); printf("cipher_text: "); for (int i = 0; i < cipher_len; i++) { printf("%02X ", cipher_text[i]); } printf("\n"); printf("result_len: %d\n", result_len); printf("result: %s\n", result); RSA_free(rsa); free(cipher_text); free(result); return 0; } ``` 这个示例代码中,我们使用 OpenSSL 库生成了一个 2048 位的 RSA 密钥对,并将公钥和私钥保存到文件中。然后我们加密了一个字符串 "Hello, RSA!",并对其进行解密,最后输出了加密前后的字符串加密后的密文。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

恋恋西风

up up up

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值