如何在Go中使用RSA密钥加密和解密纯文本? [英] How to encrypt and decrypt plain text with a RSA keys in Go?

查看:188
本文介绍了如何在Go中使用RSA密钥加密和解密纯文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个实用程序,它使用RSA密钥对加密和解密纯文本文件。 RSA密钥是用ssh-keygen生成的,像往常一样存储在.ssh中。



我很难理解如何使用Go语言加密和加密/ rsa软件包?关于这些的文档有点稀疏(更加如此,因为我是加密的新手),并且只有很少的例子。我检查了rsa_test.go文件的任何线索,但它只是让我更困惑。

简而言之,我尝试从.ssh中的id_rsa和id_rsa.pub文件中加载公钥/私钥对,并使用它们来加密/解密纯文本文件。



预先感谢您!

解决方案

请记住, RSA不是设计成分组密码。通常RSA用于加密一个对称密钥,然后用它来加密数据。但是,考虑到这一点,下面是一个程序,它可以使用RSA私钥来加密可以自行解密的数据:

  package main 

导入(
crypto / rand
crypto / rsa
crypto / sha1
crypto / x509
encoding / pem
flag
io / ioutil
log


//命令行标志
var(
keyFile = flag.String(key,id_rsa,RSA私钥的路径)
inFile = flag.String(in,in。输入文件路径)
outFile = flag.String(out,out.txt,输出文件的路径)
label = flag.String(label ,,要使用的标签(默认文件名))
解密= flag.Bool(解密,假,解密而不是加密)


func main(){
flag.Parse()

//读取输入文件
in,err:= ioutil.ReadFile(* inFile)
if err!= nil {
log.Fatalf(输入文件:%s,错误)
}

//读取私钥
pemData,err:= ioutil.ReadFile(* keyFile)
if err!= nil {
log.Fatalf(读取密钥文件:%s,err)
}

//提取PEM编码的数据块
block,_:= pem.Decode(pemData)
if block == nil {
log.Fatalf(bad key data:%s,not PEM-encoded)
}
如果有了,想要:= block.Type, RSA PRIVATE KEY; got a!= want {
log.Fatalf(未知键类型%q,想要%q,得到,想要)
}

//解码RSA私钥
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
}
//解密数据
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)
}
}

//将数据写入输出文件
if Ë rr:= ioutil.WriteFile(* outFile,out,0600); err!= nil {
log.Fatalf(write output:%s,err)
}
}


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!

解决方案

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)
    }
}

这篇关于如何在Go中使用RSA密钥加密和解密纯文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆