本文整理汇总了Golang中encoding/asn1.Unmarshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Unmarshal函数的具体用法?Golang Unmarshal怎么用?Golang Unmarshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Unmarshal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Unmarshal
func (msg *messageV3) Unmarshal(b []byte) (rest []byte, err error) {
var raw asn1.RawValue
rest, err = asn1.Unmarshal(b, &raw)
if err != nil {
return nil, err
}
if raw.Class != classUniversal || raw.Tag != tagSequence || !raw.IsCompound {
return nil, asn1.StructuralError{fmt.Sprintf(
"Invalid messageV3 object - Class [%02x], Tag [%02x] : [%s]",
raw.FullBytes[0], tagSequence, toHexStr(b, " "))}
}
next := raw.Bytes
var version int
next, err = asn1.Unmarshal(next, &version)
if err != nil {
return
}
next, err = msg.globalDataV3.Unmarshal(next)
if err != nil {
return
}
next, err = msg.securityParameterV3.Unmarshal(next)
if err != nil {
return
}
msg.version = SNMPVersion(version)
msg.pduBytes = next
return
}
示例2: getBags
// Given a slice of PKCS #7 content infos containing PKCS #12 Safe Bag Data,
// getBags returns those Safe Bags.
func getBags(authenticatedSafe []asn1.RawValue, password []byte) (bags []safeBag, err error) {
for _, contentInfo := range authenticatedSafe {
var safeContents []safeBag
bagContainer, err := pkcs7.ParsePKCS7(contentInfo.FullBytes)
if err != nil {
return nil, err
}
switch {
case bagContainer.ContentInfo == "Data":
if _, err = asn1.Unmarshal(bagContainer.Content.Data, &safeContents); err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
case bagContainer.ContentInfo == "EncryptedData":
data, err := decrypt(bagContainer.Content.EncryptedData.EncryptedContentInfo.ContentEncryptionAlgorithm,
bagContainer.Content.EncryptedData.EncryptedContentInfo.EncryptedContent, password)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
if _, err = asn1.Unmarshal(data, &safeContents); err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
default:
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("Only support for bags encoded in Data and EncryptedData types"))
}
bags = append(bags, safeContents...)
}
return bags, nil
}
示例3: convertAttribute
func convertAttribute(attribute *pkcs12Attribute) (key, value string, err error) {
key = attributeNameByOID[attribute.ID.String()]
switch {
case attribute.ID.Equal(oidMicrosoftCSPName):
fallthrough
case attribute.ID.Equal(oidFriendlyName):
if _, err = asn1.Unmarshal(attribute.Value.Bytes, &attribute.Value); err != nil {
return
}
if value, err = decodeBMPString(attribute.Value.Bytes); err != nil {
return
}
case attribute.ID.Equal(oidLocalKeyID):
id := new([]byte)
if _, err = asn1.Unmarshal(attribute.Value.Bytes, id); err != nil {
return
}
value = fmt.Sprintf("% x", *id)
default:
err = errors.New("don't know how to handle attribute with OID " + attribute.ID.String())
return
}
return key, value, nil
}
示例4: parseSignedData
func parseSignedData(data []byte) (*PKCS7, error) {
var sd signedData
asn1.Unmarshal(data, &sd)
certs, err := sd.Certificates.Parse()
if err != nil {
return nil, err
}
// fmt.Printf("--> Signed Data Version %d\n", sd.Version)
var compound asn1.RawValue
var content unsignedData
// The Content.Bytes maybe empty on PKI responses.
if len(sd.ContentInfo.Content.Bytes) > 0 {
if _, err := asn1.Unmarshal(sd.ContentInfo.Content.Bytes, &compound); err != nil {
return nil, err
}
}
// Compound octet string
if compound.IsCompound {
if _, err = asn1.Unmarshal(compound.Bytes, &content); err != nil {
return nil, err
}
} else {
// assuming this is tag 04
content = compound.Bytes
}
return &PKCS7{
Content: content,
Certificates: certs,
CRLs: sd.CRLs,
Signers: sd.SignerInfos,
raw: sd}, nil
}
示例5: ParsePKCS8PrivateKey
// ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See
// http://www.rsa.com/rsalabs/node.asp?id=2130 and RFC5208.
func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) {
var privKey pkcs8
if _, err := asn1.Unmarshal(der, &privKey); err != nil {
return nil, err
}
switch {
case privKey.Algo.Algorithm.Equal(oidPublicKeyRSA):
key, err = ParsePKCS1PrivateKey(privKey.PrivateKey)
if err != nil {
return nil, errors.New("x509: failed to parse RSA private key embedded in PKCS#8: " + err.Error())
}
return key, nil
case privKey.Algo.Algorithm.Equal(oidPublicKeyECDSA):
bytes := privKey.Algo.Parameters.FullBytes
namedCurveOID := new(asn1.ObjectIdentifier)
if _, err := asn1.Unmarshal(bytes, namedCurveOID); err != nil {
namedCurveOID = nil
}
key, err = parseECPrivateKey(namedCurveOID, privKey.PrivateKey)
if err != nil {
return nil, errors.New("x509: failed to parse EC private key embedded in PKCS#8: " + err.Error())
}
return key, nil
default:
return nil, fmt.Errorf("x509: PKCS#8 wrapping contained private key with unknown algorithm: %v", privKey.Algo.Algorithm)
}
}
示例6: parseSubjectAltName
func parseSubjectAltName(cert *certificate) (string, error) {
for _, ext := range cert.TBSCertificate.Extensions {
if ext.Id.Equal(oidExtensionSubjectAltName) {
var seq asn1.RawValue
_, err := asn1.Unmarshal(ext.Value, &seq)
if err != nil {
return "", err
}
if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
return "", asn1.StructuralError{Msg: "bad SAN sequence"}
}
var v asn1.RawValue
_, err = asn1.Unmarshal(seq.Bytes, &v)
if err != nil {
return "", err
}
if v.Tag == 6 {
return string(v.Bytes), nil
}
}
}
return "", nil
}
示例7: Unmarshal
func (pdu *PduV1) Unmarshal(b []byte) (rest []byte, err error) {
var raw asn1.RawValue
rest, err = asn1.Unmarshal(b, &raw)
if err != nil {
return
}
if raw.Class != classContextSpecific || !raw.IsCompound {
return nil, asn1.StructuralError{fmt.Sprintf(
"Invalid Pdu object - Class [%02x], Tag [%02x] : [%s]",
raw.Class, raw.Tag, toHexStr(b, " "))}
}
next := raw.Bytes
var requestId int
next, err = asn1.Unmarshal(next, &requestId)
if err != nil {
return
}
var errorStatus int
next, err = asn1.Unmarshal(next, &errorStatus)
if err != nil {
return
}
var errorIndex int
next, err = asn1.Unmarshal(next, &errorIndex)
if err != nil {
return
}
var varBinds asn1.RawValue
_, err = asn1.Unmarshal(next, &varBinds)
if err != nil {
return
}
if varBinds.Class != classUniversal || varBinds.Tag != tagSequence || !varBinds.IsCompound {
return nil, asn1.StructuralError{fmt.Sprintf(
"Invalid VarBinds object - Class [%02x], Tag [%02x] : [%s]",
varBinds.Class, varBinds.Tag, toHexStr(next, " "))}
}
next = varBinds.Bytes
for len(next) > 0 {
var varBind VarBind
next, err = (&varBind).Unmarshal(next)
if err != nil {
return
}
pdu.varBinds = append(pdu.varBinds, &varBind)
}
pdu.pduType = PduType(raw.Tag)
pdu.requestId = requestId
pdu.errorStatus = ErrorStatus(errorStatus)
pdu.errorIndex = errorIndex
return
}
示例8: ParsePKCS7
// ParsePKCS7 attempts to parse the DER encoded bytes of a
// PKCS7 structure
func ParsePKCS7(raw []byte) (msg *PKCS7, err error) {
var pkcs7 initPKCS7
_, err = asn1.Unmarshal(raw, &pkcs7)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
msg = new(PKCS7)
msg.Raw = pkcs7.Raw
msg.ContentInfo = pkcs7.ContentType.String()
switch {
case msg.ContentInfo == ObjIDData:
msg.ContentInfo = "Data"
_, err = asn1.Unmarshal(pkcs7.Content.Bytes, &msg.Content.Data)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
case msg.ContentInfo == ObjIDSignedData:
msg.ContentInfo = "SignedData"
var signedData signedData
_, err = asn1.Unmarshal(pkcs7.Content.Bytes, &signedData)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
if len(signedData.Certificates.Bytes) != 0 {
msg.Content.SignedData.Certificates, err = x509.ParseCertificates(signedData.Certificates.Bytes)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
}
if len(signedData.Crls.Bytes) != 0 {
msg.Content.SignedData.Crl, err = x509.ParseDERCRL(signedData.Crls.Bytes)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
}
msg.Content.SignedData.Version = signedData.Version
msg.Content.SignedData.Raw = pkcs7.Content.Bytes
case msg.ContentInfo == ObjIDEncryptedData:
msg.ContentInfo = "EncryptedData"
var encryptedData EncryptedData
_, err = asn1.Unmarshal(pkcs7.Content.Bytes, &encryptedData)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
if encryptedData.Version != 0 {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("Only support for PKCS #7 encryptedData version 0"))
}
msg.Content.EncryptedData = encryptedData
default:
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("Attempt to parse PKCS# 7 Content not of type data, signed data or encrypted data"))
}
return msg, nil
}
示例9: checkSignature
func checkSignature(c *x509.Certificate, algo x509.SignatureAlgorithm, signed, signature []byte) (err error) {
var hashType crypto.Hash
switch algo {
case x509.SHA1WithRSA, x509.DSAWithSHA1, x509.ECDSAWithSHA1:
hashType = crypto.SHA1
case x509.SHA256WithRSA, x509.DSAWithSHA256, x509.ECDSAWithSHA256:
hashType = crypto.SHA256
case x509.SHA384WithRSA, x509.ECDSAWithSHA384:
hashType = crypto.SHA384
case x509.SHA512WithRSA, x509.ECDSAWithSHA512:
hashType = crypto.SHA512
default:
return x509.ErrUnsupportedAlgorithm
}
if !hashType.Available() {
return x509.ErrUnsupportedAlgorithm
}
h := hashType.New()
h.Write(signed)
digest := h.Sum(nil)
switch pub := c.PublicKey.(type) {
case *rsa.PublicKey:
// the digest is already hashed, so we force a 0 here
return rsa.VerifyPKCS1v15(pub, 0, digest, signature)
case *dsa.PublicKey:
dsaSig := new(dsaSignature)
if _, err := asn1.Unmarshal(signature, dsaSig); err != nil {
return err
}
if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
return errors.New("x509: DSA signature contained zero or negative values")
}
if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
return errors.New("x509: DSA verification failure")
}
return
case *ecdsa.PublicKey:
ecdsaSig := new(ecdsaSignature)
if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
return err
}
if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
return errors.New("x509: ECDSA signature contained zero or negative values")
}
if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
return errors.New("x509: ECDSA verification failure")
}
return
}
return x509.ErrUnsupportedAlgorithm
}
示例10: main
func main() {
flag.Parse()
var contents []byte
var err error
if *file == "" {
contents, err = ioutil.ReadAll(os.Stdin)
} else {
contents, err = ioutil.ReadFile(*file)
}
if err != nil {
log.Fatal(err)
}
block, _ := pem.Decode(contents)
if block == nil {
log.Fatal("Not a PEM block.")
}
var keybytes []byte
switch block.Type {
case "PUBLIC KEY", "RSA PUBLIC KEY":
keybytes = block.Bytes
case "CERTIFICATE":
certs, err := x509.ParseCertificates(block.Bytes)
if err != nil {
log.Fatal(err)
}
if len(certs) < 1 {
log.Fatal("No certificates.")
}
keybytes = certs[0].RawSubjectPublicKeyInfo
default:
log.Fatalf("Unknown block type: %q.", block.Type)
}
hasher := sha256.New()
hasher.Write(keybytes)
fmt.Printf("sha256/%v\n", base64.StdEncoding.EncodeToString(hasher.Sum(nil)))
if *verbose {
var spki PublicKeyInfo
if _, err := asn1.Unmarshal(keybytes, &spki); err != nil {
log.Fatal(err)
}
fmt.Printf("AlgID: %v\n", spki.Algorithm.Algorithm)
var pubkey RSAPublicKey
if _, err := asn1.Unmarshal(spki.PublicKey.Bytes, &pubkey); err != nil {
log.Fatal(err)
}
fmt.Printf("N: %v\n", pubkey.N)
fmt.Printf("E: %v\n", pubkey.E)
}
}
示例11: ExtractCertificationPolicy
func ExtractCertificationPolicy(e pkix.Extension) (cps, unotice string, err error) {
if !e.Id.Equal(idCertificatePolicies) {
return "", "", fmt.Errorf("ASN OID mismatch")
}
var pi []struct {
Id asn1.ObjectIdentifier
PolicyQualifiers []struct {
Id asn1.ObjectIdentifier
Value asn1.RawValue
}
}
rest, err := asn1.Unmarshal(e.Value, &pi)
if err != nil {
return "", "", err
}
if len(rest) > 0 {
return "", "", fmt.Errorf("Trailing data after x509 Policy extension: % 02x", rest)
}
if len(pi) != 1 {
return "", "", fmt.Errorf("Unexpected count for x509 Policy extension: %d", len(pi))
}
if !pi[0].Id.Equal(idSubjectIdentityValidated) {
return "", "", fmt.Errorf("Unrecognized OID for x509 Policy extension: %v", pi[0].Id)
}
q := pi[0].PolicyQualifiers
if len(q) != 2 {
return "", "", fmt.Errorf("Unexpected count for x509 Policy extension qualifiers: %d", len(pi[0].PolicyQualifiers))
}
if !q[0].Id.Equal(idQtCertificationPracticeStatement) {
return "", "", fmt.Errorf("Unrecognized OID for x509 Policy extension CPS: %v", q[0].Id)
}
rest, err = asn1.Unmarshal(q[0].Value.FullBytes, &cps)
if err != nil {
return "", "", fmt.Errorf("Error extracting CPS: %v", err)
}
if len(rest) > 0 {
return "", "", fmt.Errorf("Trailing data after x509 Policy extension CPS: % 02x", rest)
}
if !q[1].Id.Equal(idQtUnotice) {
return "", "", fmt.Errorf("Unrecognized OID for x509 Policy extension User Notice: %v", q[1].Id)
}
if len(q[1].Value.Bytes) > 0 && q[1].Value.Bytes[0] == asn1VisibleStringTag {
q[1].Value.Bytes[0] = asn1PrintableStringTag
}
rest, err = asn1.Unmarshal(q[1].Value.Bytes, &unotice)
if err != nil {
return "", "", fmt.Errorf("Error extracting user notice: %v", err)
}
if len(rest) > 0 {
return "", "", fmt.Errorf("Trailing data after x509 Policy extension User Notice: % 02x", rest)
}
return cps, unotice, nil
}
示例12: genKey
// Generates a symmetric key and encrypts the verification token
func (client *Client) genKey() (err error) {
if client.DebugWriter != nil {
fmt.Fprintf(client.DebugWriter, "Decoding public key\n")
}
var pki publicKeyInfo
_, err = asn1.Unmarshal(client.serverKeyMessage, &pki)
if err != nil {
return err
}
client.serverKey = new(rsa.PublicKey)
_, err = asn1.Unmarshal(pki.SubjectPublicKey.Bytes, client.serverKey)
if err != nil {
return err
}
if client.DebugWriter != nil {
fmt.Fprintf(client.DebugWriter, "Generating encryption key\n")
}
/*
client.sharedSecret = make([]byte, 16)
_, err = rand.Reader.Read(client.sharedSecret)
if err != nil {
return err
}
*/
client.sharedSecret = []byte("1234567812345678")
if client.DebugWriter != nil {
fmt.Fprintf(client.DebugWriter, "Encrypting verification token\n")
}
client.encryptedVerifyToken, err = rsa.EncryptPKCS1v15(rand.Reader, client.serverKey, client.serverVerifyToken)
if err != nil {
return err
}
if client.DebugWriter != nil {
fmt.Fprintf(client.DebugWriter, "Encrypting shared secret\n")
}
client.encryptedSharedSecret, err = rsa.EncryptPKCS1v15(rand.Reader, client.serverKey, client.sharedSecret)
if err != nil {
return err
}
return nil
}
示例13: ParsePKCS12
// ParsePKCS12 parses a pkcs12 syntax object
// into a container for a private key, certificate(s), and
// version number
func ParsePKCS12(raw, password []byte) (msg *PKCS12, err error) {
msg = new(PKCS12)
password, err = pbkdf.BMPString(password)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
var Pfx pfx
_, err = asn1.Unmarshal(raw, &Pfx)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
if msg.Version = Pfx.Version; msg.Version != 3 {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("Only support for PKCS #12 PFX version 3"))
}
authSafe, err := pkcs7.ParsePKCS7(Pfx.AuthSafe.FullBytes)
if err != nil {
return nil, err
}
if authSafe.ContentInfo != "Data" {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("No support for AuthSafe Format"))
}
var authenticatedSafe []asn1.RawValue
_, err = asn1.Unmarshal(authSafe.Content.Data, &authenticatedSafe)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
if len(authenticatedSafe) != 2 {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("No support for AuthSafe Format"))
}
var bags []safeBag
bags, err = getBags(authenticatedSafe, password)
if err != nil {
return nil, err
}
if len(bags) > 2 || bags == nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("No support for AuthSafe Format"))
}
certs, pkey, err := parseBags(bags, password)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
}
msg.Certificates = certs
msg.PrivateKey = pkey
return
}
示例14: decodePublicKey
func decodePublicKey(data []byte) (key rsa.PublicKey, err error) {
var pks publicKeyStructure
_, err = asn1.Unmarshal(data, &pks)
if err != nil {
return key, err
}
if !oidsEqual(pks.Algorithm.Algorithm, rsaAlgorithm) {
return key, fmt.Errorf("Unexpected public key algorithm (object identifier %v)", pks.Algorithm.Algorithm)
}
_, err = asn1.Unmarshal(pks.SubjectPublicKey.Bytes, &key)
return key, err
}
示例15: parsePublicKey
func parsePublicKey(cert *certificate) (interface{}, error) {
pki := cert.TBSCertificate.PublicKey
algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
if algo == UnknownPublicKeyAlgorithm {
return nil, errors.New("unknown publc key algorithm")
}
keyData := &pki
asn1Data := keyData.PublicKey.RightAlign()
switch algo {
case RSA:
p := new(rsaPublicKey)
_, err := asn1.Unmarshal(asn1Data, p)
if err != nil {
return nil, err
}
pub := &rsa.PublicKey{
E: p.E,
N: p.N,
}
return pub, nil
case DSA:
var p *big.Int
_, err := asn1.Unmarshal(asn1Data, &p)
if err != nil {
return nil, err
}
paramsData := keyData.Algorithm.Parameters.FullBytes
params := new(dsaAlgorithmParameters)
_, err = asn1.Unmarshal(paramsData, params)
if err != nil {
return nil, err
}
if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
return nil, errors.New("zero or negative DSA parameter")
}
pub := &dsa.PublicKey{
Parameters: dsa.Parameters{
P: params.P,
Q: params.Q,
G: params.G,
},
Y: p,
}
return pub, nil
default:
return nil, nil
}
panic("unreachable")
}