Skip to content

Instantly share code, notes, and snippets.

@rikkix
Created May 12, 2019 01:47
Show Gist options
  • Save rikkix/e86819b9056b202a37218a40144a1e8a to your computer and use it in GitHub Desktop.
Save rikkix/e86819b9056b202a37218a40144a1e8a to your computer and use it in GitHub Desktop.
go RSA encrypt
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"io/ioutil"
"log"
)
func main() {
block,_ := ReadPEM("pu.pem")
rsaPub := MakeRSAPub(block)
secretMessage, err := ioutil.ReadFile("hello.txt")
checkErr(err)
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPub, secretMessage)
err = ioutil.WriteFile("hello_en", cipherText, 0644)
checkErr(err)
}
func MakeRSAPub(block *pem.Block) *rsa.PublicKey {
if block == nil || block.Type != "PUBLIC KEY" {
log.Fatal("failed to decode PEM block containing public key")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
checkErr(err)
switch pub := pub.(type) {
case *rsa.PublicKey:
return pub
}
return nil
}
func ReadPEM(filename string) (*pem.Block, []byte) {
pubPEMData, err := ioutil.ReadFile(filename)
checkErr(err)
return pem.Decode(pubPEMData)
}
func checkErr(err error) {
if err != nil {
log.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment