# GO加密解密RSA番外篇：生成RSA密钥

2013-01-18

《Go加密解密之RSA》

## 一、加解密流程

1、读取密钥（可以写死在一个变量中保存，也可以从一个外部文件读取）

2、通过encoding/pem中的Decode函数解析到block类型中

3、通过crypto/x509中相应的Parse方法得到密钥（即crypto/rsa包中的PrivateKey和PublicKey）

## 二、生成密钥并编码保存到文件中

func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err error)

```type PrivateKey struct {
PublicKey            // public part.
D         *big.Int   // private exponent
Primes    []*big.Int // prime factors of N, has >= 2 elements.

// Precomputed contains precomputed values that speed up private
// operations, if available.
Precomputed PrecomputedValues
}```

```type PublicKey struct {
N *big.Int // modulus
E int      // public exponent
}```

```func GenRsaKey(bits int) error {
// 生成私钥文件
if err != nil {
return err
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := &pem.Block{
Type:  "RSA PRIVATE KEY",
Bytes: derStream,
}
file, err := os.Create("private.pem")
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
// 生成公钥文件
publicKey := &privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
block = &pem.Block{
Type:  "PUBLIC KEY",
Bytes: derPkix,
}
file, err = os.Create("public.pem")
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
return nil
}```

myblog_article_code
rsa/rsa_gen_key.go这个文件

func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err error)

## 您可能感兴趣的

Accelerate SHA256 Computations in Pure Go Using AV... sha256-simd Accelerate SHA256 computations in pure Go using AVX512 and AVX2 for Intel and ARM64 for ARM. On AVX512 it provides an up to 8x improveme...

Encrypting Inside WSO2 ESB Using the AES Algorithm In integration development, you will come across instances where you need to hold a payload in an intermediate place before it reaches its final desti...
HiNet 與 DigitalOcean、Linode、Vultr 的封包情況... 先說結論，綜合網路與 CPU 的情況，我剛好跟下面提到的文章給出相反的選擇 (i.e. 完全不會選 DigitalOcean )。如果是需要 latency 低的品質我會選 Linode 的東京新機房 Tokyo 2，如果不需要 latency 的我會選 Vultr 的 USD\$2.5/mo...