本文整理汇总了Golang中golang.org/x/crypto/openpgp.ReadMessage函数的典型用法代码示例。如果您正苦于以下问题:Golang ReadMessage函数的具体用法?Golang ReadMessage怎么用?Golang ReadMessage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ReadMessage函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: DecryptFile
func (s *SftpSession) DecryptFile(fname string) (string, error) {
lr, err := os.Open(fname)
if err != nil {
return "", err
}
defer lr.Close()
/*
slurped, err := ioutil.ReadAll(lr)
if err != nil {
return "", err
}
*/
fdecrypted := strings.TrimSuffix(fname, filepath.Ext(fname))
lw, err := os.Create(fdecrypted)
if err != nil {
return "", fmt.Errorf("open file error: %s, %s\n", fdecrypted, err.Error())
}
var armorStart = []byte("-----BEGIN ")
var msg *openpgp.MessageDetails
var dcrypterr error
buf := bufio.NewReaderSize(lr, 512)
peek, err := buf.Peek(15)
if err != nil {
return "", fmt.Errorf("armor peek: %s, %s\n", fdecrypted, dcrypterr.Error())
}
if bytes.HasPrefix(peek, armorStart) {
// armored
log.Printf("armored: %s\n", fname)
// try reading in an armored block
dearmor, err := armor.Decode(buf)
if err != nil {
log.Printf("not armored: %s\n", fname)
return "", fmt.Errorf("armor read msg error: %s, %s\n", fdecrypted, dcrypterr.Error())
} else {
log.Printf("armored: %s\n", fname)
// Decrypt the dearmored message
msg, dcrypterr = openpgp.ReadMessage(dearmor.Body, s.entityList, nil, nil)
}
} else {
// Decrypt the binary message
msg, dcrypterr = openpgp.ReadMessage(buf, s.entityList, nil, nil)
}
if dcrypterr != nil {
return "", fmt.Errorf("decrypt read msg error: %s, %s\n", fdecrypted, dcrypterr.Error())
}
_, err = io.Copy(lw, msg.UnverifiedBody)
if err != nil {
return "", err
}
return fdecrypted, nil
}
示例2: Decrypt
func Decrypt(index int, kring openpgp.EntityList, keyName string, isSigned bool, filename string, passphrase []byte) (string, error) {
err := DecryptPw(kring, keyName, passphrase)
if err != nil {
return "", err
}
f2, err := os.Open(filename)
if err != nil {
logrus.Errorf("#%d: error in Create: %s", index, err)
return "", err
}
md, err := openpgp.ReadMessage(f2, kring, nil /* no prompt */, nil)
if err != nil {
logrus.Errorf("#%d: error reading message: %s", index, err)
return "", err
}
/*
testTime, _ := time.Parse("2006-01-02", "2013-07-01")
if isSigned {
signKey, _ := kring[0].signingKey(testTime)
expectedKeyId := signKey.PublicKey.KeyId
if md.SignedByKeyId != expectedKeyId {
logrus.Errorf("#%d: message signed by wrong key id, got: %d, want: %d", i, *md.SignedBy, expectedKeyId)
}
if md.SignedBy == nil {
logrus.Errorf("#%d: failed to find the signing Entity", i)
}
}
*/
plaintext, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
logrus.Errorf("#%d: error reading encrypted contents: %s", index, err)
return "", err
}
/*
encryptKey, _ := kring[0].encryptionKey(testTime)
expectedKeyId := encryptKey.PublicKey.KeyId
if len(md.EncryptedToKeyIds) != 1 || md.EncryptedToKeyIds[0] != expectedKeyId {
logrus.Errorf("#%d: expected message to be encrypted to %v, but got %#v", i, expectedKeyId, md.EncryptedToKeyIds)
}
if string(plaintext) != message {
logrus.Errorf("#%d: got: %s, want: %s", index, string(plaintext), message)
}
*/
if isSigned {
if md.SignatureError != nil {
logrus.Errorf("#%d: signature error: %s", index, md.SignatureError)
}
if md.Signature == nil {
logrus.Error("signature missing")
}
}
return string(plaintext), nil
}
示例3: Decode
// Decode - this function wraps around a Decoder object to decode the passed in data.
// @param io.Reader[] src - This parameter will be used to read the encrypted data
// @param io.Writer[] dest - This parameter will be used to write the unencrypted data
func (d *Decoder) Decode(r io.Reader, w io.Writer) error {
entitylist, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer(d.Key))
if err != nil {
return err
}
entity := entitylist[0]
if entity.PrivateKey != nil && entity.PrivateKey.Encrypted {
if len(d.Passphrase) == 0 {
return errors.New("Private key is encrypted but you did not provide a passphrase")
}
err := entity.PrivateKey.Decrypt(d.Passphrase)
if err != nil {
return errors.New("Failed to decrypt private key. Did you use the wrong passphrase? (" + err.Error() + ")")
}
}
for _, subkey := range entity.Subkeys {
if subkey.PrivateKey != nil && subkey.PrivateKey.Encrypted {
err := subkey.PrivateKey.Decrypt(d.Passphrase)
if err != nil {
return errors.New("Failed to decrypt subkey. Did you use the wrong passphrase? (" + err.Error() + ")")
}
}
}
read, err := openpgp.ReadMessage(r, entitylist, nil, nil)
if err != nil {
return err
}
_, err = io.Copy(w, read.LiteralData.Body)
return err
}
示例4: DecryptBytes
// DecryptBytes takes in base64-encoded encrypted bytes and the base64-encoded
// private key and decrypts it. A bytes.Buffer is returned to allow the caller
// to do useful thing with it (get it as a []byte, get it as a string, use it
// as an io.Reader, etc), and also because this function doesn't know if what
// comes out is binary data or a string, so let the caller decide.
func DecryptBytes(encodedCrypt, privKey string) (*bytes.Buffer, error) {
privKeyBytes, err := base64.StdEncoding.DecodeString(privKey)
if err != nil {
return nil, fmt.Errorf("Error decoding base64 private key: %s", err)
}
cryptBytes, err := base64.StdEncoding.DecodeString(encodedCrypt)
if err != nil {
return nil, fmt.Errorf("Error decoding base64 crypted bytes: %s", err)
}
entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(privKeyBytes)))
if err != nil {
return nil, fmt.Errorf("Error parsing private key: %s", err)
}
entityList := &openpgp.EntityList{entity}
md, err := openpgp.ReadMessage(bytes.NewBuffer(cryptBytes), entityList, nil, nil)
if err != nil {
return nil, fmt.Errorf("Error decrypting the messages: %s", err)
}
ptBuf := bytes.NewBuffer(nil)
ptBuf.ReadFrom(md.UnverifiedBody)
return ptBuf, nil
}
示例5: decryptString
func decryptString(decryptionString string, encryptionPassphraseString string) (string, error) {
encryptionPassphrase := []byte(encryptionPassphraseString)
decbuf := bytes.NewBuffer([]byte(decryptionString))
result, err := armor.Decode(decbuf)
if err != nil {
return "", err
}
alreadyPrompted := false
md, err := openpgp.ReadMessage(result.Body, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
if alreadyPrompted {
return nil, errors.New("Could not decrypt using passphrase")
} else {
alreadyPrompted = true
}
return encryptionPassphrase, nil
}, nil)
if err != nil {
return "", err
}
bytes, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
return "", err
}
return string(bytes), nil
}
示例6: GpgDecrypt
func GpgDecrypt(text2decrypt string) string {
encrypted := bytes.NewBuffer([]byte(text2decrypt))
bin_encrypt, err := armor.Decode(encrypted)
if err != nil {
log.Printf("[PGP] not an armored payload: %s", err.Error())
return ""
}
cleartext_md, err := openpgp.ReadMessage(bin_encrypt.Body, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
return []byte(config.GetTribeID()), nil
}, nil)
if err != nil {
log.Printf("[PGP] Can't decrypt payload: %s", err.Error())
return ""
}
plaintext, err := ioutil.ReadAll(cleartext_md.UnverifiedBody)
if err != nil {
log.Printf("[PGP] Can't read cleartext: %s", err.Error())
return ""
}
return string(plaintext)
}
示例7: Decrypt
func (o *openPGP) Decrypt(input *os.File, output *os.File, verify bool) (err error) {
keyRing := openpgp.EntityList{}
keyRing = append(keyRing, o.secKey)
if o.pubKey != nil {
keyRing = append(keyRing, o.secKey)
}
messageDetails, err := openpgp.ReadMessage(input, keyRing, nil, nil)
if err != nil {
return
}
_, err = io.Copy(output, messageDetails.UnverifiedBody)
if err != nil {
return
}
if verify && !(messageDetails.IsSigned && messageDetails.SignatureError == nil) {
return errors.New("file has been decrypted but signature verification failed")
}
return
}
示例8: Decrypt
func Decrypt(data string, key_file string) (string, error) {
secretKeyring, err := os.Open(key_file)
if err != nil {
return nil, err
}
defer secretKeyring.Close()
// Taken from crypt and adapted
decoder := base64.NewDecoder(base64.StdEncoding, bytes.NewBufferString(data))
entityList, err := openpgp.ReadArmoredKeyRing(secretKeyring)
if err != nil {
return nil, err
}
md, err := openpgp.ReadMessage(decoder, entityList, nil, nil)
if err != nil {
return nil, err
}
gzReader, err := gzip.NewReader(md.UnverifiedBody)
if err != nil {
return nil, err
}
defer gzReader.Close()
bytes, err := ioutil.ReadAll(gzReader)
if err != nil {
return nil, err
}
return string(bytes), nil
}
示例9: Fuzz
func Fuzz(data []byte) int {
md, err := openpgp.ReadMessage(bytes.NewBuffer(data), emptyKR{},
newPromptFunction(), nil)
if err != nil {
return 0
}
buf := new(bytes.Buffer)
_, err = io.Copy(buf, md.UnverifiedBody)
if err != nil {
if _, ok := err.(pgperrors.SignatureError); ok {
// The message structure is correct. It parsed
// correctly, but only failed an integrity
// check. We return 1 for it. Fully correct
// messages will return 2 below.
return 1
}
return 0
}
verifiedBody := buf.Bytes()
if !bytes.Equal(plainBytes, verifiedBody) {
// There seems to be no way of telling if an MDC was
// checked for. If there was, we could check for that
// and panic here. For now, we just assume that this
// is a non-MDC protected message that has been
// modified.
return 1
}
return 2
}
示例10: DecryptBytes
func (client PGP) DecryptBytes(esecret []byte) []byte {
md, err := openpgp.ReadMessage(bytes.NewBuffer(esecret), client.PrivateEntities, nil, nil)
if err != nil {
panic(err)
}
bytes, _ := ioutil.ReadAll(md.UnverifiedBody)
return bytes
}
示例11: main
func main() {
flag.Parse()
if cpuprofile != "" {
profFD, err := os.Create(cpuprofile)
if err != nil {
log.Fatalf("Cpuprofile: os.Create(): %v", err)
}
pprof.StartCPUProfile(profFD)
defer pprof.StopCPUProfile()
}
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP,
syscall.SIGPIPE)
go func() {
<-c
if cpuprofile != "" {
pprof.StopCPUProfile()
}
// In case we had a hang, we print the stack trace here.
buf := make([]byte, 256*1024)
n := runtime.Stack(buf, true)
fmt.Fprintln(os.Stderr, string(buf[0:n]))
os.Exit(1)
}()
var fd *os.File = os.Stdin
var err error
if filename != "" {
fd, err = os.Open(filename)
if err != nil {
log.Fatalf("Input: os.Open(): %v", err)
}
defer fd.Close()
}
md, err := openpgp.ReadMessage(fd, emptyKR{}, newPromptFunction(), nil)
if err != nil {
log.Fatalf("openpgp.ReadMessage(): %v", err)
}
log.Println("openpgp.ReadMessage() returned without error")
_, err = io.Copy(os.Stdout, md.UnverifiedBody)
if err != nil {
log.Fatalf("Reading unverified plain text: io.Copy(): %v", err)
}
// Check that any authentication code for the message was
// verified successfully
if md.SignatureError != nil {
log.Fatalln("Integrity Check FAILED:", md.SignatureError)
}
}
示例12: decryptOpenpgp
func decryptOpenpgp(data io.Reader, gpghome string, pass []byte) (io.Reader, error) {
privkeyfile, err := os.Open(fmt.Sprintf("%s%ssecring.gpg", gpghome, string(os.PathSeparator)))
if err != nil {
fmt.Println("Failed to open secring", err)
return nil, err
}
privring, err := openpgp.ReadKeyRing(privkeyfile)
if err != nil {
fmt.Println("Failed to open secring", err)
return nil, err
}
//reader := bytes.NewReader(data)
//brk,_ := ioutil.ReadAll(data)
//fmt.Println("wtf",string(brk))
//fmt.Println("here is where eof panic")
block, err := armor.Decode(data)
if err != nil {
fmt.Println(err)
panic(err)
}
if len(pass) == 0 {
fmt.Fprintf(os.Stderr, "Password: ")
pass, err = terminal.ReadPassword(0)
if err != nil {
panic(err)
}
fmt.Fprintln(os.Stderr, "")
}
for _, entity := range privring {
if entity.PrivateKey != nil && entity.PrivateKey.Encrypted {
entity.PrivateKey.Decrypt(pass)
}
for _, subkey := range entity.Subkeys {
if subkey.PrivateKey != nil && subkey.PrivateKey.Encrypted {
subkey.PrivateKey.Decrypt(pass)
}
}
}
md, err := openpgp.ReadMessage(block.Body, privring, nil, nil)
if err != nil {
return nil, err
}
return md.UnverifiedBody, nil
//plaintext, err := ioutil.ReadAll(md.UnverifiedBody)
//if err != nil {
// panic(err)
// }
// return plaintext, nil
}
示例13: main
func main() {
encrypt_out := flag.String("out", "ciphertext.out", "Ciphertext")
log.Println("Create key pair")
// Create a key-pair
entity, _ := openpgp.NewEntity("The Receiver", "testing",
"[email protected]", nil)
log.Println("Start encryption")
config := &packet.Config{
DefaultHash: crypto.SHA256,
}
file, err := os.OpenFile(*encrypt_out, os.O_WRONLY|os.O_CREATE, 0600)
// For some reason it uses RIPEMD160 ?
plain, err := openpgp.Encrypt(file, []*openpgp.Entity{entity},
nil, nil, config)
if err != nil {
log.Fatal(err)
}
// Input of plaintext: a stream (as we typically would get from a
// network stream).
plain.Write([]byte("Hello World plaintext!\n"))
plain.Close()
// Decrypt
read_file, _ := os.Open(*encrypt_out)
keyring := openpgp.EntityList{entity}
message, err := openpgp.ReadMessage(read_file, keyring,
func(keys []openpgp.Key, sym bool) ([]byte, error) {
log.Printf("Prompt got called\n")
return nil, nil
}, nil)
if err != nil {
log.Fatal(err)
}
// Read the encrypted file and dump plain-text to stdout.
body_reader := message.UnverifiedBody
buffer := make([]byte, 1024)
for {
n, _ := body_reader.Read(buffer)
if n == 0 {
break
}
os.Stdout.Write(buffer[0:n])
}
log.Println("Done.")
}
示例14: decodeBase64EncryptedMessage
func decodeBase64EncryptedMessage(s string, keyring openpgp.KeyRing) string {
// Decrypt base64 encoded encrypted message using decrypted private key
dec, err := base64.StdEncoding.DecodeString(s)
if err != nil {
log.Fatalln("ERR:", err)
}
debug.Printf("keyring: #%v", keyring)
md, err := openpgp.ReadMessage(bytes.NewBuffer(dec), keyring, nil, nil)
if err != nil {
log.Fatalln("ERR: Error reading message - ", err)
}
bytes, err := ioutil.ReadAll(md.UnverifiedBody)
debug.Printf("md:", string(bytes))
return string(bytes)
}
示例15: ReadEncrypted
func ReadEncrypted(ciphertext io.ReadCloser, el openpgp.EntityList, passphrase []byte) (io.ReadCloser, error) {
md, err := openpgp.ReadMessage(ciphertext, el, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
if symmetric {
return nil, fmt.Errorf("No support for symmetrical encryption")
}
for _, key := range keys {
if err := key.PrivateKey.Decrypt(passphrase); err != nil {
return nil, ErrCannotDecryptKey
}
return nil, nil
}
return nil, ErrNoMatchingKeys
}, nil)
if err != nil {
return nil, err
}
return &encryptedReader{ciphertext, md.UnverifiedBody}, nil
}