Package main import ("Crypto/rsa" "crypto/x509" "Encoding/pem" "Crypto/rand" "Flag" "Log" "OS") Func main () { var bits int flag. Intvar (&bits, "B", 2048, "key length, default 1024-bit") if err: = Genrsakey (bits); Err! = Nil {log. Fatal ("Key file generation failed. ")} log. PRINTLN ("Key file generation succeeded. ")} func Genrsakey (bits int) error {//Generate private key file Privatekey, err: = RSA. GenerateKey (Rand. Reader, BITS) if err! = Nil {return err} derstream: = X509. Marshalpkcs1privatekey (privatekey) Block: = &pem. block{Type: "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}//Generate public key file PublicKey: = &privatekey.publickey Derpkix, err: = X 509.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}
Package main import ("Crypto/rand" "Crypto/rsa" "crypto/x509" "Encoding/base64" "Encoding/pem" "Errors" "Flag" " FMT "" "Io/ioutil" "OS") var decrypted string var privatekey, PublicKey []byte func init () {var err error flag. Stringvar (&decrypted, "D", "", "encrypted data") flag. Parse () publickey, err = Ioutil. ReadFile ("Public.pem") if err! = nil {os. Exit ( -1)} Privatekey,err = Ioutil. ReadFile ("Private.pem") if err! = nil {os.
Exit ( -1)}} Func main () {var data []byte var err error data, err = Rsaencrypt ([]byte ("Fyxichen")) if err! = Nil { Panic (Err)} origdata, err: = Rsadecrypt (data) if err! = Nil {panic (err)} FMT. Println (String (origdata))}//cryptographic func rsaencrypt (Origdata []byte) ([]byte, error) {block, _: = Pem. Decode (publickey) if block = = Nil {return nil, errors. New ("Public Key Error")} pubinterface, err: = X509. Parsepkixpublickey (block. Bytes) If err! = Nil {return nil, err} pub: = Pubinterface. (*rsa. PublicKey) return RSA. EncRyptpkcs1v15 (Rand. Reader, Pub, Origdata)}//Decrypt Func rsadecrypt (ciphertext []byte) ([]byte, error) {block, _: = Pem. Decode (privatekey) if block = = Nil {return nil, errors.
New ("Private key error!") } priv, err: = X509. Parsepkcs1privatekey (block. Bytes) If err! = Nil {return nil, err} return RSA. Decryptpkcs1v15 (Rand.
Reader, Priv, ciphertext)}