NTL的安装、连接与使用(基于CentOS、Clion)

1、安装 m4

 sudo apt-get install m4

2、安装gmp

在网站下载gmp文件,解压 gmp-6.0.0a.tar.lz 文件,并安装。

解压 gmp 压缩包

 tar -xf gmp-6.0.0a.tar.lz

然后安装

 cd gmp-6.0.0
 ./configure
 make
 make check
 sudo make install

3、安装NTL

下载NTL(ntl-11.5.1.tar.gz)后解压,然后切换文件夹

tar ntl-11.5.1.tar.gz
cd ntl-11.5.1/src

进行安装

./configure

make

make check

sudo make install

4、检查看是否安装成功(有无ntl相关文件)

ls /usr/local/include
ls /usr/local/lib

5、打开Clion编译软件

修改cmake.list

cmake_minimum_required(VERSION 3.23)
project(test02)

set(CMAKE_CXX_STANDARD 14)
# 声明位置
LINK_DIRECTORIES(/usr/local/lib)

link_libraries(/usr/local/lib/libntl.a)
#被链接的库相对路径
link_directories(/usr/local/lib /lib)
#被链接库的头文件相对路径
include_directories(/usr/local/include)

add_executable(ecc main.cpp)

target_link_libraries(ecc -lm -lgmp -lntl -lpthread)

6、运行例子

#include<iostream>
#include<NTL/ZZ.h>
using namespace NTL;

int main(){
    ZZ p, q, n, phi_of_n, public_key, private_key, message;
    int no_of_bits;

    std::cout<<"Enter no of bits : ";
    std::cin>>no_of_bits;

    // generating p and q prime numbers
    p = GenPrime_ZZ(no_of_bits, 80);
    q = GenPrime_ZZ(no_of_bits, 80);
    n = p * q;
    phi_of_n = (p-1)*(q-1);

    ZZ i = (ZZ)1;
    long bits_of_n = 0;
	for( ; i <= n; i *= 10) { 
        bits_of_n++; 
    }

    public_key = GenPrime_ZZ(bits_of_n/2, 80);
	private_key = InvMod(public_key, phi_of_n);

    std::cout<<"
Enter Message to decrypt : ";
    std::cin>>message;

    // Encryption of message using public key
    ZZ encrypted_message = PowerMod(message, public_key, n);
    ZZ decrypted_message = PowerMod(encrypted_message, private_key, n);

    std::cout<<"
p = "<<p<<"
";
    std::cout<<"
q = "<<q<<"
";
    std::cout<<"
n = "<<n<<"
";
    std::cout<<"
phi of n = "<<phi_of_n<<"
";
    std::cout<<"
public key = "<<public_key<<"
";
    std::cout<<"
private key = "<<private_key<<"
";
    std::cout<<"
private key * public key (mod phi_of_n)= "<<MulMod(public_key, private_key, phi_of_n)<<"
";
    std::cout<<"
Encrypted Message = "<<encrypted_message<<"
";
    std::cout<<"
Decrypted Message = "<<decrypted_message<<"
";
    return 0; 
}

8、成功运行未报错,如下图所示

经验分享 程序员 微信小程序 职场和发展