半同态算法Paillier实现与性能测试

Code

type PrivateKey struct {
	Lambda *big.Int
	Mu     *big.Int
	Public *PublicKey
}

type PublicKey struct {
	N  *big.Int
	G  *big.Int
	N2 *big.Int
}

func (pub *PublicKey) Encrypt(val int64) *big.Int {
	m := big.NewInt(val)

	if val < 0 || m.Cmp(zero) == -1 || m.Cmp(pub.N) != -1 {
		panic("invalid value")
	}

	// 计算r
	r := new(big.Int)
	gcd := new(big.Int)
	mathRand := rnd.New(rnd.NewSource(time.Now().UnixNano()))
	for {
		r.Rand(mathRand, pub.N)
		if gcd.GCD(nil, nil, r, pub.N).Cmp(one) == 0 {
			break
		}
	}

	// 加密运算
	r.Exp(r, pub.N, pub.N2)
	m.Exp(pub.G, m, pub.N2)

	c := new(big.Int).Mul(m, r)
	return c.Mod(c, pub.N2)
}

// Add 同态加法
func (pub *PublicKey) Add(a, b *big.Int) *big.Int {
	if a == nil || b == nil || a.Cmp(zero) != 1 || b.Cmp(zero) != 1 {
		panic("invalid input")
	}

	z := new(big.Int).Mul(a, b)
	return z.Mod(z, pub.N2)
}

// Decrypt 解密
func (k *PrivateKey) Decrypt(c *big.Int) int64 {
	if c == nil || c.Cmp(zero) != 1 {
		panic("invalid input")
	}

	m := L(new(big.Int).Exp(c, k.Lambda, k.Public.N2), k.Public.N)
	m.Mul(m, k.Mu)
	m.Mod(m, k.Public.N)
	return m.Int64()
}

func L(x, n *big.Int) *big.Int {
	return new(big.Int).Div(new(big.Int).Sub(x, one), n)
}

func GenerateKey(rd io.Reader, bits int) (*PrivateKey, error) {
	var (
		p, q, n, lambda *big.Int
		err             error
	)
	n, lambda = new(big.Int), new(big.Int)

	for {
		p, err = rand.Prime(rd, bits)
		if err != nil {
			return nil, err
		}
		q, err = rand.Prime(rd, bits)
		if err != nil {
			return nil, err
		}
		if p.Cmp(q) == 0 {
			continue
		}

		n.Mul(p, q)
		lambda.Mul(new(big.Int).Sub(p, one), new(big.Int).Sub(q, one))

		// gcd(pq, (p-1)(q-1)) = 1
		if new(big.Int).GCD(nil, nil, n, lambda).Cmp(one) == 0 {
			break
		}
	}

	return &PrivateKey{
		Lambda: lambda,
		Mu:     new(big.Int).ModInverse(lambda, n),
		Public: &PublicKey{
			N:  n,
			G:  new(big.Int).Add(n, one),
			N2: new(big.Int).Mul(n, n),
		}}, nil
}

测试结果

ns/op 平均每个操作所用时长(单位纳秒)

  • 1s = 1000ms

  • 1ms = 1000μs

  • 1μs = 1000ns

密钥生成

  • 1024位:15703404 ns/op
  • 2048位:135691817 ns/op
  • 4096位:529907500 ns/op

同态加法

  • 1024位:3271 ns/op
  • 2048位:9456 ns/op
  • 4096位:27152 ns/op

加解密

测试数据:9223372036854775807

加密

  • 1024位:1757482 ns/op

  • 2048位:11455122 ns/op

  • 4096位:90242423 ns/op

解密

  • 1024位:1493146 ns/op
  • 2048位:11077407 ns/op
  • 4096位:88358415 ns/op
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值