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