本文整理汇总了Golang中golang.org/x/crypto/openpgp/armor.Decode函数的典型用法代码示例。如果您正苦于以下问题:Golang Decode函数的具体用法?Golang Decode怎么用?Golang Decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Decode函数的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: NewDefinitionManager
// Initialize a new DefinitionManager
// The definition manager is responsible for downloading the main.cvd and daily.cvd from
// the URLs defined above, via conditional (ETAG) requests
// In addiiton it holds the state of the download (ETAGS and signature, once verification is done)
func NewDefinitionManager() (*DefinitionsManager, error) {
// new instance of the manager
manager := new(DefinitionsManager)
// open the public key file
verificationKeyFileReader, err := os.Open("verification.key")
if err != nil {
return nil, err
}
// close the file once we are done here
defer verificationKeyFileReader.Close()
// instantiate a new File Reader
keyReader := bufio.NewReader(verificationKeyFileReader)
// if we got here then the sha256 match, we can proceed
block, err := armor.Decode(keyReader)
if err != nil {
return nil, err
}
manager.PublicKeyData = block
manager.httpCLient = http.Client{}
return manager, nil
}
示例3: TestPacketCounts
func (s *SamplePacketSuite) TestPacketCounts(c *gc.C) {
testCases := []struct {
name string
nUserID, nUserAttribute, nSubKey, nSignature int
}{{
"0ff16c87.asc", 9, 0, 1, 0,
}, {
"alice_signed.asc", 1, 0, 1, 0,
}, {
"uat.asc", 2, 1, 3, 0,
}, {
"252B8B37.dupsig.asc", 3, 0, 2, 1,
}}
for i, testCase := range testCases {
c.Logf("test#%d: %s", i, testCase.name)
f := testing.MustInput(testCase.name)
defer f.Close()
block, err := armor.Decode(f)
c.Assert(err, gc.IsNil)
var key *PrimaryKey
for keyRead := range ReadKeys(block.Body) {
key = keyRead.PrimaryKey
}
c.Assert(key, gc.NotNil)
c.Assert(key.UserIDs, gc.HasLen, testCase.nUserID)
c.Assert(key.UserAttributes, gc.HasLen, testCase.nUserAttribute)
c.Assert(key.SubKeys, gc.HasLen, testCase.nSubKey)
c.Assert(key.Signatures, gc.HasLen, testCase.nSignature)
}
}
示例4: v3KeyReader
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
}
示例5: VerifySignature
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
}
示例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: trySig
func trySig(filename string) (bool, error) {
sigFile, err := os.Open(filename)
if err != nil {
return true, err
}
defer sigFile.Close()
b, err := armor.Decode(sigFile)
if err != nil && err != io.EOF {
return true, err
}
if b == nil {
return false, nil
}
// Read the signature file
pack, err := packet.Read(b.Body)
if err != nil {
return true, err
}
// Was it really a signature file ? If yes, get the Signature
if signature, ok := pack.(*packet.Signature); !ok {
return false, nil
} else {
fmt.Printf("Signature made %s\n", signature.CreationTime.Format(time.RFC3339))
// Signature made Wed 05 Aug 2015 11:48:13 PM UTC using RSA key ID F553000C
// Primary key fingerprint: EF64 BCCB 58BC F501 FEDA 0582 0581 2930 F553 000C
// binary signature, digest algorithm SHA256
return true, nil
}
}
示例8: 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
}
示例9: ReadArmorKeys
func ReadArmorKeys(r io.Reader) (PrimaryKeyChan, error) {
block, err := armor.Decode(r)
if err != nil {
return nil, err
}
return ReadKeys(block.Body), nil
}
示例10: 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
}
示例11: TestKeyserverHKP
func TestKeyserverHKP(t *testing.T) {
kss, caPool, clks, _, ck, clientConfig, teardown := setupRealm(t, 1, 0)
ks := kss[0]
defer teardown()
stop := stoppableSyncedClocks(clks)
defer close(stop)
waitForFirstEpoch(kss[0], clientConfig.Realms[0].VerificationPolicy.GetQuorum())
clientTLS, err := clientConfig.Realms[0].ClientTLS.Config(ck)
if err != nil {
t.Fatal(err)
}
pgpKeyRef := []byte("this-is-alices-pgp-key")
doRegister(t, ks, clientConfig, clientTLS, caPool, clks[0].Now(), alice, 0, proto.Profile{
Nonce: []byte("definitely used only once"),
Keys: map[string][]byte{"pgp": pgpKeyRef},
})
tr := &http.Transport{
// TODO: identify and fix the bug with client auth and HTTP/2 and use clientTLS
// Also set HKPTLS back to proto.REQUIRE_AND_VERIFY_CLIENT_CERT
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
//TLSClientConfig: clientTLS,
}
url := "https://" + ks.hkpListen.Addr().String() + "/pks/lookup?op=get&search=" + alice
c := &http.Client{Transport: tr}
resp, err := c.Get(url)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.Status != "200 OK" {
b, e := ioutil.ReadAll(resp.Body)
t.Fatalf("%s (%s)", b, e)
}
pgpBlock, err := armor.Decode(resp.Body)
if err != nil {
t.Fatal(err)
}
if got, want := pgpBlock.Type, "PGP PUBLIC KEY BLOCK"; got != want {
t.Errorf("pgpBlock.Type: got %v but wanted %v", got, want)
}
if got, want := len(pgpBlock.Header), 0; got != want {
t.Errorf("len(pgpBlock.Header): got %v but wanted %v", got, want)
}
pgpKey, err := ioutil.ReadAll(pgpBlock.Body)
if err != nil {
t.Fatal(err)
}
if got, want := pgpKey, pgpKeyRef; !bytes.Equal(got, want) {
t.Errorf("pgpKey: got %q but wanted %q", got, want)
}
}
示例12: KeyRing
// KeyRing reads a openpgp.KeyRing from the given io.Reader which may then be
// used to validate GPG keys in RPM packages.
func KeyRing(r io.Reader) (openpgp.KeyRing, error) {
// decode gpgkey file
p, err := armor.Decode(r)
if err != nil {
return nil, err
}
// extract keys
return openpgp.ReadKeyRing(p.Body)
}
示例13: PublicKeyToPGPClient
func PublicKeyToPGPClient(publicKey string) PGPClient {
block, err := armor.Decode(strings.NewReader(publicKey))
if err != nil {
panic(err)
}
entity, err := openpgp.ReadEntity(packet.NewReader(block.Body))
if err != nil {
panic(err)
}
return PGPClient{openpgp.EntityList{entity}}
}
示例14: DecodeArmor
func DecodeArmor(armorStr string) (blockType string, headers map[string]string, data []byte, err error) {
buf := bytes.NewBufferString(armorStr)
block, err := armor.Decode(buf)
if err != nil {
return "", nil, nil, err
}
data, err = ioutil.ReadAll(block.Body)
if err != nil {
return "", nil, nil, err
}
return block.Type, block.Header, data, nil
}
示例15: TestDeduplicate
func (s *SamplePacketSuite) TestDeduplicate(c *gc.C) {
f := testing.MustInput("d7346e26.asc")
defer f.Close()
block, err := armor.Decode(f)
if err != nil {
c.Fatal(err)
}
// Parse keyring, duplicate all packet types except primary pubkey.
kr := &OpaqueKeyring{}
for opkr := range ReadOpaqueKeyrings(block.Body) {
c.Assert(opkr.Error, gc.IsNil)
for _, op := range opkr.Packets {
kr.Packets = append(kr.Packets, op)
switch op.Tag {
case 2:
kr.Packets = append(kr.Packets, op)
fallthrough
case 13, 14, 17:
kr.Packets = append(kr.Packets, op)
}
}
}
key, err := kr.Parse()
c.Assert(err, gc.IsNil)
n := 0
for _, node := range key.contents() {
c.Logf("%s", node.uuid())
n++
}
c.Log()
err = CollectDuplicates(key)
c.Assert(err, gc.IsNil)
n2 := 0
for _, node := range key.contents() {
c.Logf("%s %d", node.uuid(), node.packet().Count)
n2++
switch node.packet().Tag {
case 2:
c.Check(node.packet().Count, gc.Equals, 2)
case 13, 14, 17:
c.Check(node.packet().Count, gc.Equals, 1)
case 6:
c.Check(node.packet().Count, gc.Equals, 0)
default:
c.Fatal("should not happen")
}
}
c.Assert(n2 < n, gc.Equals, true)
}