栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

ELGamal公钥密码算法代码实现C++

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ELGamal公钥密码算法代码实现C++


#include
#include 
#include 
using namespace std;

int pow_mod(int a, int b, int p); //pow and mod运算 --核心  a的b次方mod p 
void encryption(int m, int pub_key, int p, int g, int* c1, int* c2); //加密算法 
//m--密文  pub--公钥  p--素数 g--本原元 c1、c2 --密文 
int decryption(int c1, int c2, int pub_key, int p, int g); // 解密算法
bool is_prime(int p); //判断是否为素数
 
//main函数测试 
int main() {
    int p;//素数
    int g ; //本元根 
    cout << "Please input g:";
	cin >> g; 
	cout << endl; 

    do {
        cout << "Please enter a prime number: ";
        cin>>p;
    } while (!is_prime(p));
    cout << endl;
    cout << "Enter the private key of user A: "; //A的私钥 
    int key_A;
    cin>>key_A;
    cout << endl;
    int pub; // A的公钥 
    pub = pow_mod(g, key_A, p);
    cout << "the public key of user A: "<>m;
    cout << endl; 
    int c1, c2; // 密文 
    encryption(m, pub, p, g, &c1, &c2);
    cout << "The ciphertext encrypted with the public key is:" << endl;
	cout << "c1= " << c1 << "    " << "c2= " <
    int k; //随机数
	cout << "Please input a random data: ";
	cin >> k; 
    *c1 = pow_mod(g, k, p);
    *c2 = m * pow_mod(pub_key, k, p) % p;
}
//解密算法
int decryption(int c1, int c2, int pub_key, int p, int g) {
    int m;
    int c1_ = pow_mod(c1, p - 2, p);
    m = c2 * pow_mod(c1_, pub_key, p) % p;
    return m;
}
//判断是否为素数
bool is_prime(int p) {
    int i;
    for (i = 2; i <= sqrt(p); i++) {
        if (p % i == 0)
            return false;
    }
    return true;
}

//pow and mod运算 --核心 
int pow_mod(int a, int b, int p) {
    int ans = 1;
    int tmp = a % p;
    while (b) {
        if (b & 1)
            ans = ans * tmp % p;
        b >>= 1;
        tmp = tmp * tmp % p;
    }
    return ans % p;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/923318.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号