作者:cmar
项目:hockeypuc
func testReadDigestDups(t *testing.T, testfile string) {
f := MustInput(t, "rtt-140.asc")
defer f.Close()
block, err := armor.Decode(f)
if err != nil {
t.Fatal(err)
}
var opkr *OpaqueKeyring
for kr := range ReadOpaqueKeyrings(block.Body) {
if opkr != nil {
t.Fatal("unexpected keyring")
}
opkr = kr
}
assert.Equal(t, len(opkr.Packets), 24)
pubkey, err := opkr.Parse()
assert.Nil(t, err)
var buf bytes.Buffer
err = WritePackets(&buf, pubkey)
assert.Nil(t, err)
opkr = nil
for kr := range ReadOpaqueKeyrings(bytes.NewBuffer(buf.Bytes())) {
if opkr != nil {
t.Fatal("unexpected keyring")
}
opkr = kr
}
assert.Equal(t, len(opkr.Packets), 24)
}
作者:tomzhan
项目:golang-devops-stuf
func v3KeyReader(t *testing.T) io.Reader {
armorBlock, err := armor.Decode(bytes.NewBufferString(keySigV3Armor))
if err != nil {
t.Fatalf("armor Decode failed: %v", err)
}
return armorBlock.Body
}
作者:kiso
项目:hockeypuc
// Add responds to /pks/add HKP requests.
func (w *Worker) Add(a *hkp.Add) {
// Parse armored keytext
var changes []*KeyChange
var readErrors []*ReadKeyResult
// Check and decode the armor
armorBlock, err := armor.Decode(bytes.NewBufferString(a.Keytext))
if err != nil {
a.Response() <- &ErrorResponse{err}
return
}
for readKey := range ReadKeys(armorBlock.Body) {
if readKey.Error != nil {
readErrors = append(readErrors, readKey)
} else {
change := w.UpsertKey(readKey.Pubkey)
if change.Error != nil {
log.Printf("Error updating key [%s]: %v\n", readKey.Pubkey.Fingerprint(),
change.Error)
} else {
go w.notifyChange(change)
}
changes = append(changes, change)
}
}
a.Response() <- &AddResponse{Changes: changes, Errors: readErrors}
}
作者:pombredann
项目:camlistor
func (vr *VerifyRequest) VerifySignature() bool {
armorData := reArmor(vr.CamliSig)
block, _ := armor.Decode(bytes.NewBufferString(armorData))
if block == nil {
return vr.fail("can't parse camliSig armor")
}
var p packet.Packet
var err error
p, err = packet.Read(block.Body)
if err != nil {
return vr.fail("error reading PGP packet from camliSig: " + err.Error())
}
sig, ok := p.(*packet.Signature)
if !ok {
return vr.fail("PGP packet isn't a signature packet")
}
if sig.Hash != crypto.SHA1 && sig.Hash != crypto.SHA256 {
return vr.fail("I can only verify SHA1 or SHA256 signatures")
}
if sig.SigType != packet.SigTypeBinary {
return vr.fail("I can only verify binary signatures")
}
hash := sig.Hash.New()
hash.Write(vr.bp) // payload bytes
err = vr.PublicKeyPacket.VerifySignature(hash, sig)
if err != nil {
return vr.fail(fmt.Sprintf("bad signature: %s", err))
}
vr.SignerKeyId = vr.PublicKeyPacket.KeyIdString()
return true
}
作者:jeffbryne
项目:mi
// Verify() checks the validity of a signature for some data,
// and returns a boolean set to true if valid and an OpenPGP Entity
func Verify(data string, signature string, keyring io.Reader) (valid bool, entity *openpgp.Entity, err error) {
valid = false
// re-armor signature and transform into io.Reader
sigReader := strings.NewReader(reArmor(signature))
// decode armor
sigBlock, err := armor.Decode(sigReader)
if err != nil {
panic(err)
}
if sigBlock.Type != "PGP SIGNATURE" {
err = fmt.Errorf("Wrong signature type '%s'", sigBlock.Type)
panic(err)
}
// convert to io.Reader
srcReader := strings.NewReader(data)
// open the keyring
ring, err := openpgp.ReadKeyRing(keyring)
if err != nil {
panic(err)
}
entity, err = openpgp.CheckDetachedSignature(ring, srcReader, sigBlock.Body)
if err != nil {
panic(err)
}
// we passed, signature is valid
valid = true
return
}
作者:pruthvirajsin
项目:prlpk
func TestReadKey0ff16c87(t *testing.T) {
f := MustInput(t, "0ff16c87.asc")
block, err := armor.Decode(f)
if err != nil {
t.Fatal(err)
}
var key *Pubkey
for keyRead := range ReadKeys(block.Body) {
key = keyRead.Pubkey
}
assert.NotNil(t, key)
key.Visit(func(rec PacketRecord) error {
_, err = rec.GetOpaquePacket()
switch r := rec.(type) {
case *Pubkey:
assert.NotEmpty(t, r.Packet)
case *Subkey:
assert.NotEmpty(t, r.Packet)
case *Signature:
assert.NotEmpty(t, r.Packet)
case *UserId:
assert.NotEmpty(t, r.Packet)
case *UserAttribute:
assert.NotEmpty(t, r.Packet)
}
assert.Nil(t, err)
return nil
})
}
作者:Braintree
项目:scrambl
func ReadEntity(privKeyArmor string) (*openpgp.Entity, error) {
block, err := armor.Decode(strings.NewReader(privKeyArmor))
if err != nil {
return nil, err
}
return openpgp.ReadEntity(packet.NewReader(block.Body))
}
作者:jvehen
项目:go-toybo
func main() {
sigReader := strings.NewReader(sig)
sigBlock, err := armor.Decode(sigReader)
if err != nil {
panic(err)
}
if sigBlock.Type != openpgp.SignatureType {
panic("not a signature type")
}
dataReader := strings.NewReader(data)
krfd, err := os.Open("/home/ulfr/.gnupg/pubring.gpg")
if err != nil {
panic(err)
}
defer krfd.Close()
keyring, err := openpgp.ReadKeyRing(krfd)
if err != nil {
panic(err)
}
entity, err := openpgp.CheckDetachedSignature(
keyring, dataReader, sigBlock.Body)
if err != nil {
panic(err)
}
fmt.Printf("valid signature from key %s\n",
hex.EncodeToString(entity.PrimaryKey.Fingerprint[:]))
}
作者:nymsi
项目:pgpmai
func extractEncryptedBodyMime(m *Message) (io.Reader, error) {
ps := m.mpContent.parts
if len(ps) != 2 {
return nil, fmt.Errorf("failed to extract encrypted body, expecting 2 mime parts, got %d", len(ps))
}
block, err := armor.Decode(strings.NewReader(ps[1].Body))
if err != nil {
return nil, errors.New("armor decode of encrypted body failed: " + err.Error())
}
return block.Body, nil
}
作者:Bobberin
项目:musing
// readArmored reads an armored block with the given type.
func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) {
block, err := armor.Decode(r)
if err != nil {
return
}
if block.Type != expectedType {
return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type)
}
return block.Body, nil
}
作者:temal
项目:troussea
// Decrypt tries to decrypt an OpenPGP armored block using the provided decryption keys
// and passphrase. If succesfull the plain content of the block is returned as []byte.
func Decrypt(d []byte, decryptionKeys *openpgp.EntityList, passphrase string) ([]byte, error) {
var armoredBlock *armor.Block
var message *openpgp.MessageDetails
var plain []byte
var err error
if d == nil {
return nil, nil
}
// Decode the OpenPGP armored block
armoredBlock, err = armor.Decode(bytes.NewReader(d))
if err != nil {
return nil, err
}
// Extract the message from the OpenPGP armored block
message, err = openpgp.ReadMessage(armoredBlock.Body, decryptionKeys,
func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
kp := []byte(passphrase)
if symmetric {
return kp, nil
}
for _, k := range keys {
err := k.PrivateKey.Decrypt(kp)
if err == nil {
// If no error were returned, we could succesfully
// decrypt the message using the provided private key
return nil, nil
}
}
return nil, fmt.Errorf("Unable to decrypt trousseau data store. " +
"Invalid passphrase supplied.")
},
nil)
if err != nil {
return nil, fmt.Errorf("unable to decrypt trousseau data store. " +
"No private key able to decrypt it found in your keyring.")
}
// Read the plain message bytes
plain, err = ioutil.ReadAll(message.UnverifiedBody)
if err != nil {
return nil, err
}
return plain, err
}
作者:rajasau
项目:sync_gatewa
// ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
func ReadArmoredKeyRing(r io.Reader) (EntityList, error) {
block, err := armor.Decode(r)
if err == io.EOF {
return nil, errors.InvalidArgumentError("no armored data found")
}
if err != nil {
return nil, err
}
if block.Type != PublicKeyType && block.Type != PrivateKeyType {
return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type)
}
return ReadKeyRing(block.Body)
}
作者:cmar
项目:hockeypuc
func MustInputAscKeys(t *testing.T, name string) (result []*Pubkey) {
f := MustInput(t, name)
defer f.Close()
block, err := armor.Decode(f)
if err != nil {
t.Fatal(err)
}
for keyRead := range ReadKeys(block.Body) {
if keyRead.Error != nil {
t.Fatal(keyRead.Error)
}
result = append(result, keyRead.Pubkey)
}
return
}
作者:nymsi
项目:pgpmai
func extractInlineBody(body string) (io.Reader, error) {
start := strings.Index(body, beginPgpMessage)
if start == -1 {
return nil, nil
}
end := strings.Index(body, endPgpMessage)
if end == -1 {
return nil, errors.New("End of inline PGP message not found")
}
armored := body[start:(end + len(endPgpMessage))]
block, err := armor.Decode(bytes.NewReader([]byte(armored)))
if err != nil {
return nil, errors.New("armor decode of encrypted body failed: " + err.Error())
}
return block.Body, nil
}
作者:pruthvirajsin
项目:prlpk
func TestValidateKey(t *testing.T) {
f := MustInput(t, "tails.asc")
defer f.Close()
block, err := armor.Decode(f)
if err != nil {
t.Fatal(err)
}
var keys []*Pubkey
for keyRead := range ReadKeys(block.Body) {
keys = append(keys, keyRead.Pubkey)
}
assert.Equal(t, 1, len(keys))
assert.Equal(t, 2, len(keys[0].userIds))
for i := 0; i < 2; i++ {
assert.NotEmpty(t, keys[0].userIds[i].ScopedDigest)
}
}
作者:josca
项目:sync_gatewa
// Test packet.Read error handling in OpaquePacket.Parse,
// which attempts to re-read an OpaquePacket as a supported
// Packet type.
func TestOpaqueParseReason(t *testing.T) {
armorBlock, err := armor.Decode(bytes.NewBufferString(UnsupportedKeyArmor))
if err != nil {
t.Fatalf("armor Decode failed: %v", err)
}
or := NewOpaqueReader(armorBlock.Body)
count := 0
badPackets := 0
var uid *UserId
for {
op, err := or.Next()
if err == io.EOF {
break
} else if err != nil {
t.Errorf("#%d: opaque read error: %v", count, err)
break
}
// try to parse opaque packet
p, err := op.Parse()
switch pkt := p.(type) {
case *UserId:
uid = pkt
case *OpaquePacket:
// If an OpaquePacket can't re-parse, packet.Read
// certainly had its reasons.
if pkt.Reason == nil {
t.Errorf("#%d: opaque packet, no reason", count)
} else {
badPackets++
}
}
count++
}
const expectedBad = 2
// Test post-conditions, make sure we actually parsed packets as expected.
if badPackets != expectedBad {
t.Errorf("unexpected # unparseable packets: %d (want %d)", badPackets, expectedBad)
}
if uid == nil {
t.Errorf("failed to find expected UID in unsupported keyring")
} else if uid.Id != "Armin M. Warda <[email protected]>" {
t.Errorf("unexpected UID: %v", uid.Id)
}
}
作者:pruthvirajsin
项目:prlpk
func DelegateToSKS(searchquery string, toServer string) (keys []*Pubkey, err error) {
resp, errG := http.Get(fmt.Sprintf("http://" + toServer + "/pks/lookup?op=get&search=" + searchquery))
if errG != nil {
err = errG
return
}
if resp.StatusCode == http.StatusNotFound {
return
}
// Store response in memory. Connection may timeout if we
// read directly from it while loading.
var body *bytes.Buffer
{
defer resp.Body.Close()
bodyBuf, errR := ioutil.ReadAll(resp.Body)
if errR != nil {
log.Println("Delegate: Reading http response body:", errR)
err = errR
return
}
body = bytes.NewBuffer(bodyBuf)
}
// Check and decode the armor
armorBlock, errD := armor.Decode(body)
if errD != nil {
log.Println("armor.decode", err)
return
}
for readKey := range ReadKeys(armorBlock.Body) {
if readKey.Error != nil {
fmt.Println("ReadKeys", readKey.Error)
} else {
log.Println("delegate.go: Found a key from request!! = ", readKey.Pubkey.KeyId())
//fmt.Println("delegate.go: Found a key from request!! = ", readKey.Pubkey.KeyId())
keys = append(keys, readKey.Pubkey)
}
}
return
}
作者:nymsi
项目:pgpmai
func verifyMimeSignature(m *Message, keysrc KeySource) *VerifyStatus {
if !m.IsMultipart() || m.ctSecondary != "signed" {
return createVerifyFailure("Not a multipart/signed message")
}
ps := m.mpContent.parts
if len(ps) != 2 {
return createVerifyFailure(fmt.Sprintf("cannot extract signature, expecting 2 mime parts, got %d", len(ps)))
}
sig := bytes.NewReader([]byte(ps[1].Body))
sigBlock, err := armor.Decode(sig)
if err != nil {
return createVerifyFailure("error decoding armored signature: " + err.Error())
}
status := checkSignature(keysrc, ps[0].rawContent, sigBlock)
if isVerifiedSignature(status) {
processMimePlaintext(m, ps[0].rawContent)
status.Message = m
}
return status
}
作者:nymsi
项目:nyms-verifie
func loadPGPKey(path string, defaultPath string) (*openpgp.Entity, error) {
if path == "" {
path = getHomePath(defaultPath)
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
block, err := armor.Decode(f)
if err != nil {
return nil, err
}
el, err := openpgp.ReadKeyRing(block.Body)
if err != nil {
return nil, err
}
if len(el) != 1 {
return nil, fmt.Errorf("Key file %s contained %d keys, expecting 1", path, len(el))
}
return el[0], nil
}
作者:pruthvirajsin
项目:prlpk
func TestUatRtt(t *testing.T) {
f := MustInput(t, "uat.asc")
defer f.Close()
block, err := armor.Decode(f)
if err != nil {
t.Fatal(err)
}
var p packet.Packet
for {
p, err = packet.Read(block.Body)
if err != nil {
break
}
if uat, is := p.(*packet.UserAttribute); is {
var buf bytes.Buffer
uat.Serialize(&buf)
or := packet.NewOpaqueReader(bytes.NewBuffer(buf.Bytes()))
op, _ := or.Next()
assert.Equal(t, buf.Bytes()[3:], op.Contents)
}
}
}