C語言實現RSA加解密算法

jopen 9年前發布 | 4K 次閱讀 C/C++ 算法
  1. RSA說明
    RSA公鑰加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美國麻省理工學院)開發的。RSA取名來自開發他們三者的名字。
    RSA算法基于一個十分簡單的數論事實:將兩個大素數相乘十分容易,但那時想要對其乘積進行因式分解卻極其困難,因此可以將乘積公開作為加密密鑰。
    2. RSA算法實現
    RSA算法是一種非對稱密碼算法,所謂非對稱,就是指該算法需要一對密鑰,使用其中一個加密,則需要用另一個才能解密。
    RSA的算法涉及三個參數,n、e1、e2。
    其中,n是兩個大質數p、q的積,n的二進制表示時所占用的位數,就是所謂的密鑰長度。
    e1和e2是一對相關的值,e1可以任意取,但要求e1與(p-1)(q-1)互質;再選擇e2,要求(e2e1)mod((p-1)*(q-1))=1。
    (n,e1),(n,e2)就是密鑰對。其中 (n,e1)為公鑰,(n,e2)為私鑰。
    RSA加解密的算法完全相同,設A為明文,B為密文,則:A=B^e1 mod n;B=A^e2 mod n;
    e1和e2可以互換使用,即:A=B^e2 mod n;B=A^e1 mod n;
    /**
  2. Copyright(c) tcpipstack
  3. File Name : RSA.c
  4. Abstract Description : RSA加解密算法的簡單演示
  5. Create Date : 2010/08/17
  6. Author : tcpipstack *-------------------------Revision History--------------------------------------------------
  7. No Version Date Revised By Item Description
  8. 1 1.0 10/08/17 * **/ #include <stdio.h> #include <math.h>

/ RSA算法中加密方公布的密鑰是N和E,解密方使用N和D解密 /

define P 5 / P和Q必須為素數,在實際運用中通常為很大的數 /

define Q 7

define N (PQ) / add the (), or will cause the mistake */

define Z ((P - 1)*(Q - 1))

define E 5 / 加密方選擇E,E必須和Z只有一個公約數 /

define D 5 / (E D - 1)必須能夠被Z整除 */

                /* 由于long int無法表示過大的數字,所以D取5 */


void main(void) { int i; int TrsMsg[4] = {12, 15, 22, 5}; long en[4], de[4]; int SecCode[4], DeMsg[4];

printf("下面是一個RSA加解密算法的簡單演示:\n\n");
printf("報文\t加密\t   加密后密文\n");

for (i=0; i<4; i++)
{
    /* s = m(E) mod N */
    en[i] = (int)pow(TrsMsg[i], E);
    SecCode[i] = en[i] % N;

    printf("%d\t%d\t\t%d\n", TrsMsg[i], en[i], SecCode[i]);
}

printf("\n原始報文\t密文\t\t\t解密報文\n");
for (i=0; i<4; i++)
{
    /* d = s(D) mod N */
    de[i] = pow(SecCode[i], D);
    DeMsg[i] = de[i] % N;

    printf("%d\t\t%d\t%d\t\t%d\n", TrsMsg[i], SecCode[i], de[i], DeMsg[i]);
}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!