openssl rsa加解密例程

2021-09-07 02:19:09 字數 2692 閱讀 4633

openssl是可以很方便加密解密的庫,可以使用它來對需要在網路中傳輸的資料加密。可以使用非對稱加密:公鑰加密,私鑰解密。openssl提供了對rsa的支援,但rsa存在計算效率低的問題,所以一般的做法是使用對稱金鑰加密資料,然後再把這個只在當前有效的臨時生成的對稱金鑰用非對稱金鑰的公鑰加密之後傳遞給目標方,目標方使用約定好的非對稱金鑰中的私鑰解開,得到資料加密的金鑰,再進行資料解密,得到資料,這種使用方式很常見,可以認為是對https的裁剪。對稱金鑰加密可以選擇aes,比des更優秀。

產生動態庫的做法:

1、安裝activeperl

2、進入openssl所在資料夾,執行:perl configure vc-win32 --prefix=c:\openssl-dll

3、進入vc/bin目錄,執行 vcvars32.bat 設定環境變數

4、返回openssl目錄,執行 ms\do_ms

5、在openssl目錄下執行編譯 nmake -f ms\ntdll.mak

6、把必要生成物拷貝到prefix定義的目錄中 nmake -f ms\ntdll.mak install

注意:可以通過修改ntdll.mak檔案中的cflag,確定編譯mt、md庫

產生靜態庫的做法:

1、安裝activeperl

2、perl configure vc-win32 --prefix=c:\openssl-lib

3、ms\do_ms.bat

4、nmake -f ms\nt.mak

5、nmake -f ms\nt.mak install

注意:可以通過修改nt.mak檔案中的cflag,確定編譯mt、md庫。重編的時候把生成物刪掉。

rsa加解密需要先用openssl工具生成rsa公鑰和rsa私鑰。方法:

1、生成密匙檔案(包含公鑰和私鑰):openssl genrsa -out privkey.pem 1024

2、提取密匙檔案中的公鑰:openssl rsa -in privkey.pem -pubout

1024只是測試用,使用2048位才比較安全。

rsa加密部分**demo:

std::string encodersakeyfile( const std::string& strpemfilename, const std::string& strdata )

file* hpubkeyfile = null;

if(fopen_s(&hpubkeyfile, strpemfilename.c_str(), "rb") || hpubkeyfile == null)

std::string strret;

rsa* prsapublickey = rsa_new();

if(pem_read_rsa_pubkey(hpubkeyfile, &prsapublickey, 0, 0) == null)

int nlen = rsa_size(prsapublickey);

char* pencode = new char[nlen + 1];

int ret = rsa_public_encrypt(strdata.length(), (const unsigned char*)strdata.c_str(), (unsigned char*)pencode, prsapublickey, rsa_pkcs1_padding);

if (ret >= 0)

delete pencode;

rsa_free(prsapublickey);

fclose(hpubkeyfile);

crypto_cleanup_all_ex_data();

return strret;

}rsa解密部分**demo:

std::string decodersakeyfile( const std::string& strpemfilename, const std::string& strdata )

file* hprikeyfile = null;

if(fopen_s(&hprikeyfile, strpemfilename.c_str(),"rb") || hprikeyfile == null)

std::string strret;

rsa* prsaprikey = rsa_new();

if(pem_read_rsaprivatekey(hprikeyfile, &prsaprikey, 0, 0) == null)

int nlen = rsa_size(prsaprikey);

char* pdecode = new char[nlen+1];

int ret = rsa_private_decrypt(strdata.length(), (const unsigned char*)strdata.c_str(), (unsigned char*)pdecode, prsaprikey, rsa_pkcs1_padding);

if(ret >= 0)

delete pdecode;

rsa_free(prsaprikey);

fclose(hprikeyfile);

crypto_cleanup_all_ex_data();

return strret;

}rsa的api中當使用引數rsa_pkcs1_padding時,明文長度不能大於密文長度-11;

當使用引數rsa_no_padding時,明文長度需要正好是128。

加解密方法

imports system imports system.security.cryptography imports system.text imports system.io public class encryptor private shared iv as byte private sha...

加解密簡介

加密技術,簽名技術的需要做到三防一確認。一防竊聽,二防篡改,三防抵賴,確認對方身份。在電子商務過程中,開始時必須確認對方身份,不然談了半天,發現網際網路那頭真是一條狗,就悲劇了。防竊聽是指,即便有人在網路傳輸過程中得到了資料,看到的也是亂七八糟,無法從中得知正常的資訊。舉個例子,談判前老總通過網路跟...

字元加解密

using system using system.security.cryptography using system.web.security using system.io using system.text using system.configuration namespace x.com...