passforios-gopenpgp/crypto/message.go

273 lines
7.4 KiB
Go
Raw Normal View History

package crypto
2018-06-04 16:05:14 -07:00
import (
"bytes"
"errors"
2019-05-13 12:42:29 +00:00
"fmt"
2018-11-22 10:53:14 +01:00
"io"
2018-06-04 16:05:14 -07:00
"io/ioutil"
2019-03-07 16:56:12 +01:00
"math"
2018-06-04 16:05:14 -07:00
"time"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
2019-03-07 16:56:12 +01:00
pgpErrors "golang.org/x/crypto/openpgp/errors"
2018-09-19 11:52:14 +02:00
"golang.org/x/crypto/openpgp/packet"
2019-03-07 16:56:12 +01:00
2019-05-13 14:07:18 +02:00
armorUtils "github.com/ProtonMail/gopenpgp/armor"
"github.com/ProtonMail/gopenpgp/constants"
"github.com/ProtonMail/gopenpgp/internal"
"github.com/ProtonMail/gopenpgp/models"
)
2018-06-04 16:05:14 -07:00
// DecryptMessageStringKey decrypts encrypted message use private key (string)
2018-06-04 16:05:14 -07:00
// encryptedText : string armored encrypted
// privateKey : armored private use to decrypt message
// passphrase : match with private key to decrypt message
2019-05-14 18:05:01 +02:00
func (pgp *GopenPGP) DecryptMessageStringKey(
encryptedText, privateKey, passphrase string,
) (string, error) {
2018-09-19 11:52:14 +02:00
privKeyRaw, err := armorUtils.Unarmor(privateKey)
2018-06-04 16:05:14 -07:00
if err != nil {
return "", err
}
2018-11-09 02:03:19 +01:00
privKeyReader := bytes.NewReader(privKeyRaw)
privKeyEntries, err := openpgp.ReadKeyRing(privKeyReader)
if err != nil {
return "", err
}
2019-05-14 18:05:01 +02:00
return pgp.DecryptMessage(encryptedText, &KeyRing{entities: privKeyEntries}, passphrase)
2018-06-04 16:05:14 -07:00
}
2019-03-07 16:56:12 +01:00
// DecryptMessage decrypts encrypted string using keyring
2018-06-04 16:05:14 -07:00
// encryptedText : string armored encrypted
2019-05-13 12:33:01 +00:00
// privateKey : keyring with private key to decrypt message, could be multiple keys
2018-06-04 16:05:14 -07:00
// passphrase : match with private key to decrypt message
2019-05-14 18:05:01 +02:00
func (pgp *GopenPGP) DecryptMessage(encryptedText string, privateKey *KeyRing, passphrase string) (string, error) {
md, err := decryptCore(encryptedText, nil, privateKey, passphrase, pgp.getTimeGenerator())
2018-06-04 16:05:14 -07:00
if err != nil {
return "", err
}
decrypted := md.UnverifiedBody
b, err := ioutil.ReadAll(decrypted)
if err != nil {
return "", err
}
return string(b), nil
}
func decryptCore(
encryptedText string, additionalEntries openpgp.EntityList,
privKey *KeyRing, passphrase string,
timeFunc func() time.Time,
) (*openpgp.MessageDetails, error) {
2018-06-04 16:05:14 -07:00
rawPwd := []byte(passphrase)
2019-05-13 12:42:29 +00:00
if err := privKey.Unlock(rawPwd); err != nil {
err = fmt.Errorf("gopenpgp: cannot decrypt passphrase: %v", err)
2019-05-13 12:42:29 +00:00
return nil, err
}
2018-06-04 16:05:14 -07:00
privKeyEntries := privKey.entities
2018-06-04 16:05:14 -07:00
if additionalEntries != nil {
privKeyEntries = append(privKeyEntries, additionalEntries...)
}
encryptedio, err := internal.Unarmor(encryptedText)
if err != nil {
return nil, err
}
config := &packet.Config{Time: timeFunc}
md, err := openpgp.ReadMessage(encryptedio.Body, privKeyEntries, nil, config)
return md, err
}
2019-05-13 12:33:01 +00:00
// DecryptMessageVerify decrypts message and verify the signature
// encryptedText: string armored encrypted
// verifierKey []byte: unarmored verifier keys
// privateKeyRing []byte: unarmored private key to decrypt. could be multiple
// passphrase: match with private key to decrypt message
2019-05-14 18:05:01 +02:00
func (pgp *GopenPGP) DecryptMessageVerify(
encryptedText string, verifierKey, privateKeyRing *KeyRing,
passphrase string, verifyTime int64,
) (*models.DecryptSignedVerify, error) {
out := &models.DecryptSignedVerify{}
2018-06-04 16:05:14 -07:00
out.Verify = failed
var verifierEntries openpgp.EntityList
if len(verifierKey.entities) == 0 {
2018-06-04 16:05:14 -07:00
out.Verify = noVerifier
}
md, err := decryptCore(
encryptedText,
verifierEntries,
privateKeyRing,
passphrase,
func() time.Time { return time.Unix(0, 0) }) // TODO: I doubt this time is correct
if err != nil {
return nil, err
}
2018-06-04 16:05:14 -07:00
decrypted := md.UnverifiedBody
b, err := ioutil.ReadAll(decrypted)
if err != nil {
return nil, err
}
processSignatureExpiration(md, verifyTime)
2018-06-04 16:05:14 -07:00
out.Plaintext = string(b)
if md.IsSigned {
if md.SignedBy != nil {
if len(verifierKey.entities) > 0 {
matches := verifierKey.entities.KeysById(md.SignedByKeyId)
if len(matches) > 0 {
if md.SignatureError == nil {
out.Verify = ok
} else {
out.Message = md.SignatureError.Error()
out.Verify = failed
}
}
2018-06-04 16:05:14 -07:00
} else {
out.Verify = noVerifier
2018-06-04 16:05:14 -07:00
}
} else {
out.Verify = noVerifier
}
} else {
out.Verify = notSigned
}
return out, nil
}
// processSignatureExpiration handles signature time verification manually, so we can add a margin to the
// creationTime check.
func processSignatureExpiration(md *openpgp.MessageDetails, verifyTime int64) {
2019-03-07 16:56:12 +01:00
if md.SignatureError == pgpErrors.ErrSignatureExpired {
if verifyTime > 0 {
created := md.Signature.CreationTime.Unix()
expires := int64(math.MaxInt64)
2019-04-27 07:22:10 +02:00
if md.Signature.SigLifetimeSecs != nil {
expires = int64(*md.Signature.SigLifetimeSecs) + created
}
2018-09-19 11:52:14 +02:00
if created-internal.CreationTimeOffset <= verifyTime && verifyTime <= expires {
md.SignatureError = nil
}
} else {
// verifyTime = 0: time check disabled, everything is okay
md.SignatureError = nil
}
}
}
2019-05-13 12:33:01 +00:00
// EncryptMessageWithPassword encrypts a plain text to pgp message with a password
// plainText string: clear text
// output string: armored pgp message
2019-05-14 18:05:01 +02:00
func (pgp *GopenPGP) EncryptMessageWithPassword(plainText string, password string) (string, error) {
2018-11-09 02:03:19 +01:00
var outBuf bytes.Buffer
2019-03-07 16:56:12 +01:00
w, err := armor.Encode(&outBuf, constants.PGPMessageHeader, internal.ArmorHeaders)
2018-11-09 02:03:19 +01:00
if err != nil {
return "", err
}
2019-05-14 18:05:01 +02:00
config := &packet.Config{Time: pgp.getTimeGenerator()}
2018-11-09 02:03:19 +01:00
plaintext, err := openpgp.SymmetricallyEncrypt(w, []byte(password), nil, config)
if err != nil {
return "", err
}
message := []byte(plainText)
_, err = plaintext.Write(message)
2018-06-04 16:05:14 -07:00
if err != nil {
return "", err
}
2018-11-09 02:03:19 +01:00
err = plaintext.Close()
if err != nil {
return "", err
}
w.Close()
return outBuf.String(), nil
2018-06-04 16:05:14 -07:00
}
// EncryptMessage encrypts message with unarmored public key, if pass private key and passphrase will also sign
// the message
2018-06-04 16:05:14 -07:00
// publicKey : bytes unarmored public key
// plainText : the input
// privateKey : optional required when you want to sign
2019-05-13 12:33:01 +00:00
// passphrase : optional required when you pass the private key and this passphrase should decrypt the private key
// trim : bool true if need to trim new lines
2019-05-14 18:05:01 +02:00
func (pgp *GopenPGP) EncryptMessage(
plainText string, publicKey, privateKey *KeyRing,
passphrase string, trim bool,
) (string, error) {
2018-06-05 15:26:55 -07:00
if trim {
plainText = internal.TrimNewlines(plainText)
2018-06-05 15:26:55 -07:00
}
2018-06-04 16:05:14 -07:00
var outBuf bytes.Buffer
2019-03-07 16:56:12 +01:00
w, err := armor.Encode(&outBuf, constants.PGPMessageHeader, internal.ArmorHeaders)
2018-06-04 16:05:14 -07:00
if err != nil {
return "", err
}
var signEntity *openpgp.Entity
2018-11-09 02:03:19 +01:00
if len(passphrase) > 0 && len(privateKey.entities) > 0 {
var err error
signEntity, err = privateKey.GetSigningEntity(passphrase)
if err != nil {
return "", err
2018-06-04 16:05:14 -07:00
}
}
2019-05-14 18:05:01 +02:00
ew, err := EncryptCore(w, publicKey.entities, signEntity, "", false, pgp.getTimeGenerator())
if err != nil {
return "", err
}
2018-06-04 16:05:14 -07:00
_, err = ew.Write([]byte(plainText))
2018-06-04 16:05:14 -07:00
ew.Close()
w.Close()
return outBuf.String(), err
2018-06-04 16:05:14 -07:00
}
2018-11-21 23:44:33 +01:00
2019-05-13 12:33:01 +00:00
// DecryptMessageWithPassword decrypts a pgp message with a password
// encrypted string : armored pgp message
// output string : clear text
2019-05-14 18:05:01 +02:00
func (pgp *GopenPGP) DecryptMessageWithPassword(encrypted string, password string) (string, error) {
2018-11-21 23:44:33 +01:00
encryptedio, err := internal.Unarmor(encrypted)
if err != nil {
return "", err
}
firstTimeCalled := true
2018-11-21 23:44:33 +01:00
var prompt = func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
if firstTimeCalled {
firstTimeCalled = false
return []byte(password), nil
}
return nil, errors.New("password incorrect")
2018-11-21 23:44:33 +01:00
}
2019-05-14 18:05:01 +02:00
config := &packet.Config{Time: pgp.getTimeGenerator()}
2018-11-21 23:44:33 +01:00
md, err := openpgp.ReadMessage(encryptedio.Body, nil, prompt, config)
if err != nil {
return "", err
}
messageBuf := bytes.NewBuffer(nil)
_, err = io.Copy(messageBuf, md.UnverifiedBody)
if err != nil {
return "", err
}
return messageBuf.String(), nil
}