arnaucube
arnaucube/cryptofunPublic Self-hosted repository
cryptofun/rsa/rsa.go
rsa/rsa.goRaw
 1package rsa
 2
 3import (
 4	"bytes"
 5	"math/big"
 6	"math/rand"
 7	"time"
 8
 9	prime "../prime"
10)
11
12const (
13	MaxPrime = 2000
14	MinPrime = 500
15)
16
17type PublicKey struct {
18	E *big.Int `json:"e"`
19	N *big.Int `json:"n"`
20}
21type PublicKeyString struct {
22	E string `json:"e"`
23	N string `json:"n"`
24}
25type PrivateKey struct {
26	D *big.Int `json:"d"`
27	N *big.Int `json:"n"`
28}
29
30type Key struct {
31	PubK  PublicKey
32	PrivK PrivateKey
33}
34
35func GenerateKeyPair() (key Key) {
36	rand.Seed(time.Now().Unix())
37	p := prime.RandPrime(MinPrime, MaxPrime)
38	q := prime.RandPrime(MinPrime, MaxPrime)
39
40	n := p * q
41	phi := (p - 1) * (q - 1)
42	e := 65537
43	var pubK PublicKey
44	pubK.E = big.NewInt(int64(e))
45	pubK.N = big.NewInt(int64(n))
46
47	d := new(big.Int).ModInverse(big.NewInt(int64(e)), big.NewInt(int64(phi)))
48
49	var privK PrivateKey
50	privK.D = d
51	privK.N = big.NewInt(int64(n))
52
53	key.PubK = pubK
54	key.PrivK = privK
55	return key
56}
57
58func Encrypt(m *big.Int, pubK PublicKey) *big.Int {
59	Me := new(big.Int).Exp(m, pubK.E, nil)
60	c := new(big.Int).Mod(Me, pubK.N)
61	return c
62}
63func Decrypt(c *big.Int, privK PrivateKey) *big.Int {
64	Cd := new(big.Int).Exp(c, privK.D, nil)
65	m := new(big.Int).Mod(Cd, privK.N)
66	return m
67}
68
69func Blind(m *big.Int, r *big.Int, pubK PublicKey) *big.Int {
70	rE := new(big.Int).Exp(r, pubK.E, nil)
71	mrE := new(big.Int).Mul(m, rE)
72	mBlinded := new(big.Int).Mod(mrE, pubK.N)
73	return mBlinded
74}
75
76func BlindSign(m *big.Int, privK PrivateKey) *big.Int {
77	sigma := new(big.Int).Exp(m, privK.D, privK.N)
78	return sigma
79}
80func Unblind(sigma *big.Int, r *big.Int, pubK PublicKey) *big.Int {
81	r1 := new(big.Int).ModInverse(r, pubK.N)
82	bsr := new(big.Int).Mul(sigma, r1)
83	sig := new(big.Int).Mod(bsr, pubK.N)
84	return sig
85}
86func Verify(msg *big.Int, mSigned *big.Int, pubK PublicKey) bool {
87	//decrypt the mSigned with pubK
88	Cd := new(big.Int).Exp(mSigned, pubK.E, nil)
89	m := new(big.Int).Mod(Cd, pubK.N)
90	return bytes.Equal(msg.Bytes(), m.Bytes())
91}
92
93func HomomorphicMul(c1 *big.Int, c2 *big.Int, pubK PublicKey) *big.Int {
94	c1c2 := new(big.Int).Mul(c1, c2)
95	n2 := new(big.Int).Mul(pubK.N, pubK.N)
96	d := new(big.Int).Mod(c1c2, n2)
97	return d
98}