您的位置:首页 > 其它

HDOJ-1211 RS(数论)

2015-07-27 15:14 316 查看
这道题介绍了一种叫做RSA的加密解密算法,非常有趣的。最近开始学习数论,正好拿来入门。

关于RSA算法

1、选择两个大素数p,q

2、令n=p*q,Fn=(p-1) * (q-1)

3、选择一个数e,满足1<e<Fn,且e与Fn互质,称e为公钥(没学过密码学,不知道是不是这么叫)

4、找出一个d,满足 (d*e)%Fn=1,d称为私钥

加密过程:

明文为m,密文为c,则c=m^e mod n

解密过程:

m=c^d mod n

顺便介绍一下关于乘法逆元的概念(form 百度百科):
http://baike.baidu.com/link?url=NsMydjfeEwieDdFDC6DcNm6ccuJ5gn7wS9tIjdTuxIq4CGjouzeTFuRBpksJPG1SGPq-vINrKJVtxPBeSsWy5_
简单来说,就是给出a和n,求x,满足 (a*x)%n=1

不难看出RSA中的第四步求d,就是求乘法逆元。

求乘法逆元可以用扩展欧几里得算法

(扩展欧几里得算法用来求 ax+by=gcd(a,b) 中的x和y)

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef long long LL;

const int MAXL = 1E5;
LL text[MAXL+5];

//计算 ax+by=gcd(a,b),返回gcd值,求出xy
LL Ex_gcd(LL a, LL b, LL &x, LL &y)
{
    LL d;
    if(a==0 && b==0) return -1;// 无GCD
    if(b==0)
    {
        x = 1;
        y = 0;
        return a;
    }
    d = Ex_gcd(b, a%b, y, x);
    y -= a / b * x;
    return d;
}

//ax = 1(mod n)
//求a关于模n的逆元,不存在返回-1
LL Mod_reverse(LL a, LL n)
{
    LL x, y, d;
    d = Ex_gcd(a, n, x, y);
    if(d==1)
        return (x % n + n)%n;
    else
        return -1;
}

//快速幂,计算x^n
LL quickpow(LL x, LL n, LL base)
{
    LL t,res;
    res = 1;
    t = x;
    while(n)
    {
        if(n&1) res = (res * t) % base;
        n >>= 1;
        t = (t * t) % base;
    }
    return res;
}

//读入并解密
void work(LL p, LL q, LL e, LL l)
{
    LL i, n, Fn, d;
    for(i = 0; i < l; i++)
        scanf("%I64d",&text[i]);
    n = p * q;
    Fn = (p -1) * (q - 1);
    d = Mod_reverse(e, Fn);
    for(i = 0; i < l; i++)
    {
        text[i]=quickpow(text[i],d,n);
        printf("%c",text[i]);
    }
    printf("\n");
}

int main()
{
    LL p,q,e,l;
    while(~scanf("%I64d%I64d%I64d%I64d",&p,&q,&e,&l))
        work(p,q,e,l);
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: