doubi3996 2013-01-18 17:56
浏览 67
已采纳

如何在Go中使用RSA密钥加密和解密纯文本?

I am trying to write a utility program which encrypts and decrypts plain text files using a RSA key pair. The RSA keys were generated with ssh-keygen and are stored in .ssh, as usual.

I am having trouble understanding how to do that with the Go language crypto and crypto/rsa packages? The documentation on those is a little sparse (even more so because I am new to encryption) and there are very few examples. I checked the rsa_test.go file for any clues, but it only confused me more.

In short I am trying to load the public/private key pair from the id_rsa and id_rsa.pub files in .ssh and use them to encrypt/decrypt a plain text file.

Thank you in advance!

  • 写回答

1条回答 默认 最新

  • doukou4066 2013-02-18 20:00
    关注

    Keep in mind that RSA is not designed to be a block cipher. Usually RSA is used to encrypt a symmetric key that is then used to encrypt the data. With that in mind, however, here is a program which can use an RSA private key to encrypt data that can be decrypted by itself:

    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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥15 QFILHelper怎么恢复全字库,提示进程已完成,只能恢复分区文件
  • ¥150 求 《小魔指》街机游戏机整合模拟软件
  • ¥20 你好,我想问下easyExcel下拉多选,或者复选框可以实现吗
  • ¥20 双非跨考工科哪个专业和方向就业前景好?