首先介紹下命令台下openssl工具的簡單使用:
1)生成乙個金鑰:
openssl genrsa -out test.key 1024
這裡-out指定生成檔案的。需要注意的是這個檔案包含了公鑰和金鑰兩部分,也就是說這個檔案即可用來加密也可以用來解密。後面的1024是生成金鑰的長度。
2)openssl可以將這個檔案中的公鑰提取出來:
openssl rsa -in test.key -pubout -out test_pub.key
-in指定輸入檔案,-out指定提取生成公鑰的檔名。至此,我們手上就有了乙個公鑰,乙個私鑰(包含公鑰)。現在可以將用公鑰來加密檔案了。
3)在目錄中建立乙個hello的文字檔案,然後利用此前生成的公鑰加密檔案:
openssl rsautl -encrypt -in hello -inkey test_pub.key -pubin -out hello.en
-in指定要加密的檔案,-inkey指定金鑰,-pubin表明是用純公鑰檔案加密,-out為加密後的檔案。
4)解密檔案:
openssl rsautl -decrypt -in hello.en -inkey test.key -out hello.de
-in指定被加密的檔案,-inkey指定私鑰檔案,-out為解密後的檔案。
至此,一次加密解密的過程告終。
採用api加密
1. 本程式使用2048位金鑰對,每次加密時,原始資料的最大長度為245位元組,加密後的密文長度為256位元組.(採用打padding 的加密方式)
2. 如果所加密資料長度大於245位元組,請分多次加密,後將密文按順序儲存;解密時,每次讀取256位元組,進行解密,將解密後的資料依次按順序儲存,即可還原原始資料.
#include
#include
#include
#include
#include
#include
#include
#define opensslkey "test.key"
#define publickey "test_pub.key"
#define buffsize 1024
char *my_encrypt(char *str, char *path_key); //加密
char *my_decrypt(char *str, char *path_key); //解密
int main(void)
else
//2.解密
ptf_de = my_decrypt(ptf_en, opensslkey);
if (ptf_de == null)else
if(ptf_en) free(ptf_en);
if(ptf_de) free(ptf_de);
return
0; }
//加密
char *my_encrypt(char *str, char *path_key)
//2.從公鑰中獲取 加密的秘鑰
if((p_rsa = pem_read_rsa_pubkey(file, null,null,null )) == null)
lenth = strlen(str);
p_en = (char *)malloc(256);
if(!p_en)
memset(p_en, 0, 256);
//5.對內容進行加密
if(rsa_public_encrypt(lenth, (unsigned
char*)str, (unsigned
char*)p_en, p_rsa, rsa_pkcs1_padding) < 0)
end:
//6.釋放秘鑰空間, 關閉檔案
if(p_rsa) rsa_free(p_rsa);
if(file) fclose(file);
return p_en;
}
//解密
char *my_decrypt(char *str, char *path_key)
//2.從私鑰中獲取 解密的秘鑰
if((p_rsa = pem_read_rsaprivatekey(file, null,null,null )) == null)
p_de = (char *)malloc(245);
if(!p_de)
memset(p_de, 0, 245);
//5.對內容進行加密
if(rsa_private_decrypt(256, (unsigned
char*)str, (unsigned
char*)p_de, p_rsa, rsa_pkcs1_padding) < 0)
end:
//6.釋放秘鑰空間, 關閉檔案
if(p_rsa) rsa_free(p_rsa);
if(file) fclose(file);
return p_de;
}
R語言讀寫中文編碼方式
r語言讀寫資料的方法很多,這裡主要是我在使用read.csv read.table和write.csv write.table時遇到的一些中文格式編碼的問題。常見的中文編碼方式兩種 gbk gb2312 和utf 8。windows系統下 read.csv 和read.table 方法不指定檔案格式...
R語言解決MongoDB中文編碼問題
r語言的中文支援不好,採用的編碼方式常常優先考慮西方語言,中有介紹 而mongodb中儲存的中文採用的是utf 8格式編碼,因此 p mongo.find.all mongo,ns temp unlist p 1,2 讀出的資料temp中,中文無法顯示操作 將中文改變編碼格式的函式是 encodin...
來自 Google 的 R 語言編碼風格指南
r 語言是一門主要用於統計計算和繪圖的高階程式語言。這份 r 語言編碼風格指南旨在讓我們的 r 更容易閱讀 分享和檢查。以下規則系與 google 的 r 使用者群體協同設計而成。概要 r編碼風格約定 一 表示和命名 二 語法 三 組織 概要 r語言使用規則 四 語言 五 例外 六 結語 七 參考文...