Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

//GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥
	//Reader是一个全局、共享的密码用强随机数生成器
	var bits = 2048
	priKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		panic(err)
	}
	x509Key := x509.MarshalPKCS1PrivateKey(priKey)
	priKeyFile, err := os.Create("pk.pem")
	if err != nil {
		panic(err)
	}
	defer priKeyFile.Close()
	priKeyBlock := pem.Block{Type: "RSA Private Key", Bytes: x509Key}

	pem.Encode(priKeyFile, &priKeyBlock)

	x509PubKey := x509.MarshalPKCS1PublicKey(&priKey.PublicKey)

	pubKeyFile, err := os.Create("pubKey.pem")
	if err != nil {
		panic(err)
	}
	defer pubKeyFile.Close()
	pubKeyBlock := pem.Block{Type: "RSA Public Key", Bytes: x509PubKey}
	// block 输出到文件
	pem.Encode(pubKeyFile, &pubKeyBlock)
	x := pem.EncodeToMemory(&pubKeyBlock)
	log.Println(string(x))