Created
November 2, 2021 14:27
-
-
Save raypendergraph/f00e095d806f0891d0f38084f264708e to your computer and use it in GitHub Desktop.
Toy RSA implementation in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/big" | |
) | |
func encrypt(plainText string, e, n int) (cipherText []int) { | |
for _, p := range plainText { | |
//Exp sets c = p**e mod |n| | |
c := new(big.Int). | |
Exp(big.NewInt(int64(p)), big.NewInt(int64(e)), big.NewInt(int64(n))). | |
Int64() | |
cipherText = append(cipherText, int(c)) | |
} | |
return | |
} | |
func decrypt(cipherText []int, d, n int) (plainText []byte) { | |
for _, c := range cipherText { | |
//Exp sets m = c**d mod |n| | |
m := new(big.Int). | |
Exp(big.NewInt(int64(c)), big.NewInt(int64(d)), big.NewInt(int64(n))). | |
Int64() | |
plainText = append(plainText, byte(m)) | |
} | |
return | |
} | |
func main() { | |
//https://simple.wikipedia.org/wiki/RSA_algorithm#A_working_example | |
p := 61 //1 | |
q := 53 //1 | |
n := p * q //2 modulus | |
totient := (q - 1) * (p - 1) //3 https://mathworld.wolfram.com/TotientFunction.html | |
e := 17 //4 exponent (coprime) | |
d := int(new(big.Int). //5 private exponent | |
ModInverse(big.NewInt(int64(e)), big.NewInt(int64(totient))). | |
Int64()) | |
plainText := "Please never implement your own encryption.\n" | |
cipherText := encrypt(plainText, e, n) // (e, n) is called a "public key" | |
decodedText := string(decrypt(cipherText, d, n)) // (d) is called the "private key" | |
fmt.Printf("Is identical: %t, text: %s", decodedText == plainText, decodedText) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment