paillier同态加密算法库地址:
https://github.com/FISCO-BCOS/paillier-lib
开发示例
// generate the key pair for encrypt and decrypt
KeyPair keypair = PaillierKeyPair.generateGoodKeyPair();
RSAPublicKey pubKey = (RSAPublicKey)keypair.getPublic();
RSAPrivateKey priKey = (RSAPrivateKey)keypair.getPrivate();
// encrypt the first number with public key
BigInteger i1 = BigInteger.valueOf(1000000);
String c1 = PaillierCipher.encrypt(i1, pubKey);
// encrypt the second number with same public key
BigInteger i2 = BigInteger.valueOf(2012012012);
String c2 = PaillierCipher.encrypt(i2, pubKey);
// paillier add with numbers
String c3 = PaillierCipher.ciphertextAdd(c1,c2);
// decrypt the result
BigInteger o3 = PaillierCipher.decrypt(c3, priKey);
其中,生成并用于加密的公钥为:
RSAPublicKey 类型
生成并用于解密的私钥为:
RSAPrivateKey 类型
但实际上使用 keypair 的 get 方法得到的公私密钥就是 security 库中常用的普通 PublicKey 和 PrivateKey ,只是进行了强制类型转换,相关操作可以直接参考。
import java.security.*;
获取公钥字符串
可以使用如下方法:
PaillierKeyPair.publicKeyToPem()
KeyPair keypair = PaillierKeyPair.generateGoodKeyPair();
RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic();
RSAPrivateKey priKey = (RSAPrivateKey) keypair.getPrivate();
System.out.println("RSAPublicKey");
String pubstr = PaillierKeyPair.publicKeyToPem(pubKey);
System.out.println(pubstr);
结果:
获取私钥字符串
可以使用如下方法:
PaillierKeyPair.privateKeyToPem()
KeyPair keypair = PaillierKeyPair.generateGoodKeyPair();
RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic();
RSAPrivateKey priKey = (RSAPrivateKey) keypair.getPrivate();
System.out.println("RSAPrivat