package main
import (
"crypto/rsa"
"crypto/rand"
"crypto/x509"
"os"
"encoding/pem"
"crypto"
"crypto/sha256"
"fmt"
)
func rsaGenKey(publicPath string,privatePath string,bits int) error {
privateKey,err:=rsa.GenerateKey(rand.Reader,bits)
if err!=nil {
return err
}
privateKeyStream:=x509.MarshalPKCS1PrivateKey(privateKey)
privateFile,err:=os.Create(privatePath)
if err!=nil {
return err
}
defer privateFile.Close()
err=pem.Encode(privateFile,&pem.Block{
Type:"RSA Private Key",
Bytes:privateKeyStream,
})
if err!=nil {
return err
}
publicKey:=privateKey.PublicKey
publicKeyStream:=x509.MarshalPKCS1PublicKey(&publicKey)
publicFile,err:=os.Create(publicPath)
if err!=nil {
return err
}
defer publicFile.Close()
err=pem.Encode(publicFile,&pem.Block{
Type:"RSA Public Key",
Bytes:publicKeyStream,
})
if err!=nil {
return err
}
return nil
}
func signature(x string,privatePath string) ([]byte,error) {
privateFile,err:=os.Open(privatePath)
if err!=nil {
return nil,err
}
defer privateFile.Close()
fileinfo,err:=os.Stat(privatePath)
if err!=nil {
return nil,err
}
m:=make([]byte,fileinfo.Size())
privateFile.Read(m)
block,_:=pem.Decode(m)
privateKey,err:=x509.ParsePKCS1PrivateKey(block.Bytes)
if err!=nil {
return nil,err
}
mhash:=sha256.New()
mhash.Write([]byte(x))
y:=mhash.Sum(nil)
z,err:=rsa.SignPKCS1v15(rand.Reader,privateKey,crypto.SHA256,y)
if err!=nil {
return nil,err
}
return z,nil
}
func verify(x string,publicPath string,src []byte) error {
publicFile,err:=os.Open(publicPath)
if err!=nil {
return err
}
defer publicFile.Close()
fileinfo,err:=os.Stat(publicPath)
if err!=nil {
return err
}
m:=make([]byte,fileinfo.Size())
publicFile.Read(m)
block,_:=pem.Decode(m)
if err!=nil {
return err
}
publicKey,err:=x509.ParsePKCS1PublicKey(block.Bytes)
if err!=nil {
return err
}
mhash:=sha256.New()
mhash.Write([]byte(x))
y:=mhash.Sum(nil)
err=rsa.VerifyPKCS1v15(publicKey,crypto.SHA256,y,src)
if err!=nil {
return err
}
return nil
}
func main() {
privatePath:="private181115.pem"
publicPath:="public181115.pem"
err:=rsaGenKey(publicPath,privatePath,3072)
if err!=nil {
fmt.Print(err)
return
}
x1:="anti-collectivism"
z,err:=signature(x1,privatePath)
if err!=nil {
fmt.Print(err)
return
}
x2:="anti-collectivism"
err=verify(x2,publicPath,z)
if err!=nil {
fmt.Print(err)
return
}
fmt.Print("ok")
}