We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

RSA Key Generation

Something you never want to do in the real world is to write your own cryptography code from scratch. Always use well-tested crypto libraries in production.

That said, we've been asked at Passly to write our own RSA from scratch to compare against the Go standard library's implementation. Don't worry, it's just for benchmarking purposes.

Generating Big Numbers

First of all, we need to generate some really big numbers. Go has a library for that: math/big. It's a bit tricky to use, but we'll figure it out together.

  1. 2 very large prime numbers are generated, we'll call them p and q
  2. The first part of the public key is generated by multiplying p and q together, we'll call this n

Assignment

Complete the generatePrivateNums and getN functions.

func generatePrivateNums(keysize int) (*big.Int, *big.Int)

Use the provided getBigPrime function to generate two prime numbers of the given keysize in bits. Be sure to generate p first, as we're relying on the determinism of the random number generator. (Normally we would use the crypto/rand package's rand.Prime if we wanted true randomness).

func getN(p, q *big.Int) *big.Int

Use the math/big package's .Mul method to multiply p and q together to get n.

Notes

Big Integers

Notice that we're using *big.Int instead of int or int64. That's because we need to be able to handle numbers that are too big to fit in a regular integer. Most of the arithmetic with big integers is done through methods on the *big.Int type, and they mutate the pointer receiver.

Those Numbers Are Huge

You might notice that it takes a minute or so to generate those numbers, and that's because they're really big. Think about a 600-digit number! That's a 1 followed by 599 zeroes.