Skip to content

Instantly share code, notes, and snippets.

@julienXX
Created February 11, 2020 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julienXX/e9b6646cdfe96b6ff449dfd017f2f714 to your computer and use it in GitHub Desktop.
Save julienXX/e9b6646cdfe96b6ff449dfd017f2f714 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha512"
"crypto/x509"
"encoding/pem"
"fmt"
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
type Buffer struct {
Type string `json:"type"`
Data []byte `json:"data"`
}
type JsonOut struct {
Key Buffer `json:"key"`
Iv Buffer `json:"iv"`
}
func main() {
e := echo.New()
cors := middleware.CORSWithConfig(middleware.DefaultCORSConfig)
e.Use(cors)
e.POST("/download-text", func(c echo.Context) error {
body := echo.Map{}
if err := c.Bind(&body); err != nil {
return err
}
publicKey := body["public"].(string)
key, iv := generateKey(publicKey)
out := &JsonOut{
Key: Buffer{Type: "Buffer", Data: []byte(key)},
Iv: Buffer{Type: "Buffer", Data: []byte(iv)},
}
return c.JSON(http.StatusOK, out)
})
e.Logger.Fatal(e.Start(":3001"))
}
func generateKey(publicKey string) ([]byte, []byte) {
key := string(randomBytes(32))
iv := randomBytes(16)
encrypted := EncryptWithPublicKey([]byte(key), BytesToPublicKey([]byte(publicKey)))
return encrypted, iv
}
func EncryptWithPublicKey(msg []byte, pub *rsa.PublicKey) []byte {
hash := sha512.New()
ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, msg, nil)
if err != nil {
fmt.Println(err)
}
return ciphertext
}
func BytesToPublicKey(pub []byte) *rsa.PublicKey {
block, _ := pem.Decode(pub)
enc := x509.IsEncryptedPEMBlock(block)
b := block.Bytes
var err error
if enc {
fmt.Println("is encrypted pem block")
b, err = x509.DecryptPEMBlock(block, nil)
if err != nil {
fmt.Println(err)
}
}
ifc, err := x509.ParsePKIXPublicKey(b)
if err != nil {
fmt.Println(err)
}
key, ok := ifc.(*rsa.PublicKey)
if !ok {
fmt.Println("not ok")
}
return key
}
func randomBytes(size int) []byte {
b := make([]byte, size)
_, err := rand.Read(b)
if err != nil {
fmt.Println("error:", err)
return make([]byte, 0)
}
return b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment