Add decryptMime and refactor package structure

This commit is contained in:
Kay Lukas 2018-09-11 11:09:28 +02:00
parent 07b3a2c739
commit 97e70855b8
27 changed files with 516 additions and 486 deletions

33
key/fingerprint.go Normal file
View file

@ -0,0 +1,33 @@
package key
import (
"bytes"
"encoding/hex"
"errors"
"golang.org/x/crypto/openpgp"
"proton/pmcrypto/armor"
)
// GetFingerprint get a armored public key fingerprint
func GetFingerprint(publicKey string) (string, error) {
rawPubKey, err := armor.UnArmor(publicKey)
if err != nil {
return "", err
}
return GetFingerprintBinKey(rawPubKey)
}
// GetFingerprintBinKey get a unarmored public key fingerprint
func GetFingerprintBinKey(publicKey []byte) (string, error) {
pubKeyReader := bytes.NewReader(publicKey)
pubKeyEntries, err := openpgp.ReadKeyRing(pubKeyReader)
if err != nil {
return "", err
}
for _, e := range pubKeyEntries {
fp := e.PrimaryKey.Fingerprint
return hex.EncodeToString(fp[:]), nil
}
return "", errors.New("Can't find public key")
}

78
key/key.go Normal file
View file

@ -0,0 +1,78 @@
package key
import (
"strings"
"golang.org/x/crypto/openpgp"
"fmt"
"golang.org/x/crypto/openpgp/packet"
"bytes"
"proton/pmcrypto/armor"
)
//CheckPassphrase check is private key passphrase ok
func CheckPassphrase(privateKey string, passphrase string) bool {
privKeyReader := strings.NewReader(privateKey)
entries, err := openpgp.ReadArmoredKeyRing(privKeyReader)
if err != nil {
fmt.Println(err)
return false
}
var keys []*packet.PrivateKey
for _, e := range entries {
keys = append(keys, e.PrivateKey)
}
var decryptError error
var n int
for _, key := range keys {
if !key.Encrypted {
continue // Key already decrypted
}
if decryptError = key.Decrypt([]byte(passphrase)); decryptError == nil {
n++
}
}
if n == 0 {
return false
}
return true
}
// PublicKey get a public key from a private key
func PublicKey(privateKey string) (string, error) {
privKeyReader := strings.NewReader(privateKey)
entries, err := openpgp.ReadArmoredKeyRing(privKeyReader)
if err != nil {
return "", err
}
var outBuf bytes.Buffer
for _, e := range entries {
e.Serialize(&outBuf)
}
outString, err := armor.ArmorWithType(outBuf.Bytes(), armor.PUBLIC_KEY_HEADER)
if err != nil {
return "", nil
}
return outString, nil
}
// PublicKeyBinOut get a public key from a private key
func PublicKeyBinOut(privateKey string) ([]byte, error) {
privKeyReader := strings.NewReader(privateKey)
entries, err := openpgp.ReadArmoredKeyRing(privKeyReader)
if err != nil {
return nil, err
}
var outBuf bytes.Buffer
for _, e := range entries {
e.Serialize(&outBuf)
}
return outBuf.Bytes(), nil
}