我正在尝试编写一个使用RSA密钥对加密和解密纯文本文件的实用程序。RSA密钥是使用ssh-keygen生成的,并照常存储在.ssh中。
我在理解如何使用Go语言crypto和crypto / rsa软件包时遇到问题吗?有关这些文档的文档很少(甚至更多,因为我对加密还不熟悉),并且示例很少。我检查了rsa_test.go文件是否有任何线索,但这只会使我更加困惑。
简而言之,我试图从.ssh中的id_rsa和id_rsa.pub文件中加载公钥/私钥对,并使用它们对明文文件进行加密/解密。
先感谢您!
请记住,RSA并非设计为分组密码。通常,RSA用于加密对称密钥,然后将其用于加密数据。考虑到这一点,下面是一个程序,该程序可以使用RSA私钥来加密可以自己解密的数据:
package main import ( "crypto/rand" "crypto/rsa" "crypto/sha1" "crypto/x509" "encoding/pem" "flag" "io/ioutil" "log" ) // Command-line flags var ( keyFile = flag.String("key", "id_rsa", "Path to RSA private key") inFile = flag.String("in", "in.txt", "Path to input file") outFile = flag.String("out", "out.txt", "Path to output file") label = flag.String("label", "", "Label to use (filename by default)") decrypt = flag.Bool("decrypt", false, "Decrypt instead of encrypting") ) func main() { flag.Parse() // Read the input file in, err := ioutil.ReadFile(*inFile) if err != nil { log.Fatalf("input file: %s", err) } // Read the private key pemData, err := ioutil.ReadFile(*keyFile) if err != nil { log.Fatalf("read key file: %s", err) } // Extract the PEM-encoded data block block, _ := pem.Decode(pemData) if block == nil { log.Fatalf("bad key data: %s", "not PEM-encoded") } if got, want := block.Type, "RSA PRIVATE KEY"; got != want { log.Fatalf("unknown key type %q, want %q", got, want) } // Decode the RSA private key priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { log.Fatalf("bad private key: %s", err) } var out []byte if *decrypt { if *label == "" { *label = *outFile } // Decrypt the data out, err = rsa.DecryptOAEP(sha1.New(), rand.Reader, priv, in, []byte(*label)) if err != nil { log.Fatalf("decrypt: %s", err) } } else { if *label == "" { *label = *inFile } out, err = rsa.EncryptOAEP(sha1.New(), rand.Reader, &priv.PublicKey, in, []byte(*label)) if err != nil { log.Fatalf("encrypt: %s", err) } } // Write data to output file if err := ioutil.WriteFile(*outFile, out, 0600); err != nil { log.Fatalf("write output: %s", err) } }