1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| package main
import ( "fmt" "math" "math/rand" "time" )
const LIMIT = 10000
func main() { fmt.Println("generating p and q:") p, q := genPQ() fmt.Printf("p: %v q: %v\n", p, q) N := p * q eulerN := euler(p, q) fmt.Printf("N: %v eulerN: %v\n", N, eulerN) fmt.Println("calculating e and d") e, d := genED(eulerN) fmt.Printf("e: %v d:%v\n", e, d) r := rand.New(rand.NewSource(time.Now().UnixNano()))
random := r.Intn(LIMIT) fmt.Printf("generate random integer:%v\n", random)
c := encrypt(random, e, N) m := decrypt(c, d, N)
fmt.Printf("c: %v m:%v\n", c, m)
fmt.Println("encrypt sting:\n") en := encryptString("hello,我是按照逐个字节加密的", e, N) fmt.Printf("encrypt sting to []int:%v\n", en) fmt.Printf("decrypt string:%v \n", decryptString(en, d, N)) }
func isPrime(n int) bool { sn := int(math.Sqrt(float64(n))) for i := 2; i <= sn; i++ { if n%i == 0 { return false } } return true }
func genPQ() (int, int) { primechan := make(chan int) r := rand.New(rand.NewSource(time.Now().UnixNano())) count := 0 for i := 0; i < 2; i++ { go func() { for { p := r.Intn(LIMIT) if isPrime(p) { primechan <- p count++ break } } if count == 2 { close(primechan) } }() } pq := make([]int, 0, 2) for { p, ok := <-primechan if !ok { break } pq = append(pq, p) } return pq[0], pq[1] }
func euler(p int, q int) int { return (p - 1) * (q - 1) }
func exgcd(a int, b int, x *int, y *int) int { if b == 0 { *x, *y = 1, 0 return a } r := exgcd(b, a%b, x, y) *x, *y = *y, *x-a/b*(*y) return r }
func genED(eulerN int) (int, int) { r := rand.New(rand.NewSource(time.Now().UnixNano())) var d, y int for { e := r.Intn(LIMIT) if e < eulerN && exgcd(e, eulerN, &d, &y) == 1 && d > 0 { return e, d } } }
func encrypt(m int, e int, N int) int { c := 1 m = m % N for i := 1; i <= e; i++ { c = (c * m) % N } c = c % N return c }
func decrypt(c int, d int, N int) int { return encrypt(c, d, N) }
func encryptString(data string, e int, N int) []int { en := make([]int, 0, 10) databyte := []byte(data) length := len(databyte) for i := 0; i < length; i++ { c := encrypt(int(databyte[i]), e, N) en = append(en, c) } return en }
func decryptString(en []int, d int, N int) string { de := make([]byte, 0, 10) length := len(en) for i := 0; i < length; i++ { m := decrypt(en[i], d, N) de = append(de, byte(m)) } return string(de) }
|