コード例 #1
1
ファイル: message.go プロジェクト: mgenov/snmpgo
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
0
ファイル: pkcs12.go プロジェクト: JoeHorn/boulder
// 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
0
ファイル: message.go プロジェクト: mgenov/snmpgo
func (msg *messageV1) Unmarshal(b []byte) (rest []byte, err error) {
	var raw asn1.RawValue
	rest, err = asn1.Unmarshal(b, &raw)
	if err != nil {
		return
	}
	if raw.Class != classUniversal || raw.Tag != tagSequence || !raw.IsCompound {
		return nil, asn1.StructuralError{fmt.Sprintf(
			"Invalid messageV1 object - Class [%02x], Tag [%02x] : [%s]",
			raw.Class, raw.Tag, toHexStr(b, " "))}
	}

	next := raw.Bytes

	var version int
	next, err = asn1.Unmarshal(next, &version)
	if err != nil {
		return
	}

	var community []byte
	next, err = asn1.Unmarshal(next, &community)
	if err != nil {
		return
	}

	msg.version = SNMPVersion(version)
	msg.Community = community
	msg.pduBytes = next
	return
}
コード例 #4
0
ファイル: pkcs12.go プロジェクト: haneric21/go-pkcs12
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
}
コード例 #5
0
ファイル: pkcs7.go プロジェクト: GauntletWizard/vault
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
}
コード例 #6
0
ファイル: pkcs8.go プロジェクト: awesome-security/zgrab
// 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)
	}
}
コード例 #7
0
ファイル: cert.go プロジェクト: jonasp/go-webid
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
}
コード例 #8
0
ファイル: pdu.go プロジェクト: yulianghsueh/snmpgo
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
}
コード例 #9
0
ファイル: pkcs7.go プロジェクト: bretthoerner/boulder
// 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

}
コード例 #10
0
ファイル: crypto.go プロジェクト: martin61/i2p-tools
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
}
コード例 #11
0
ファイル: main.go プロジェクト: ArielBadichi/pinhash
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)
	}
}
コード例 #12
0
ファイル: x509txt.go プロジェクト: kevinawalsh/taoca
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
}
コード例 #13
0
ファイル: server.go プロジェクト: Syfaro/mc
// 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
}
コード例 #14
0
ファイル: pkcs12.go プロジェクト: JoeHorn/boulder
// 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

}
コード例 #15
0
ファイル: rsapubkey.go プロジェクト: kierdavis/proxy
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
}
コード例 #16
0
ファイル: cert.go プロジェクト: jonasp/go-webid
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")
}
コード例 #17
0
ファイル: pkcs10.go プロジェクト: cloudbuy/pkcs10
func ParsePKCS10CSR(der []byte) (csr *CertificationRequest, err error) {
	var p pkcs10
	if _, err := asn1.Unmarshal(der, &p); err != nil {
		return nil, err
	}

	certReq := &CertificationRequest{
		Version:            p.Info.Version,
		Signature:          p.Sig.Bytes,
		SignatureAlgorithm: getSignatureAlgorithmFromOID(p.Algo.Algorithm),
	}

	certReq.SubjectKeyAlgorithm = getPublicKeyAlgorithmFromOID(p.Info.SubjectInfo.Algorithm.Algorithm)

	pubKey, err := parsePublicKey(certReq.SubjectKeyAlgorithm, &p.Info.SubjectInfo)
	if err != nil {
		return nil, err
	}
	certReq.SubjectKey = pubKey
	certReq.Subject.FillFromRDNSequence(&p.Info.Subject)

	rest := p.Info.Attributes.Bytes
	for {
		if len(rest) == 0 {
			break
		}

		var a attribute
		rest, err = asn1.Unmarshal(rest, &a)
		if err != nil {
			return nil, err
		}

		var i interface{}
		_, err := asn1.Unmarshal(a.Value.Bytes, &i)
		if err != nil {
			return nil, err
		}

		attr := &Attribute{
			Name:  getAttributeNameFromOID(a.Name),
			Value: i,
		}

		certReq.Attributes = append(certReq.Attributes, attr)
	}

	return certReq, nil
}
コード例 #18
0
ファイル: asn1.go プロジェクト: rlmcpherson/go-fuzz
func Fuzz(data []byte) int {
	ctors := []func() interface{}{
		func() interface{} { return new(int) },
		func() interface{} { return new(int32) },
		func() interface{} { return new(int64) },
		func() interface{} { return new(*big.Int) },
		func() interface{} { return new(asn1.BitString) },
		func() interface{} { return new([]byte) },
		func() interface{} { return new(asn1.ObjectIdentifier) },
		func() interface{} { return new(asn1.Enumerated) },
		func() interface{} { return new(interface{}) },
		func() interface{} { return new(string) },
		func() interface{} { return new(time.Time) },
		func() interface{} { return new([]interface{}) },
		func() interface{} { return new(X) },
	}
	score := 0
	for _, ctor := range ctors {
		v := ctor()
		_, err := asn1.Unmarshal(data, v)
		if err != nil {
			continue
		}
		score = 1
		x := reflect.ValueOf(v).Elem().Interface()
		if x == nil {
			continue // https://github.com/golang/go/issues/11127
		}
		data1, err := asn1.Marshal(x)
		if err != nil {
			panic(err)
		}
		v1 := ctor()
		rest, err := asn1.Unmarshal(data1, v1)
		if err != nil {
			panic(err)
		}
		if len(rest) != 0 {
			fmt.Printf("data: %q\n", rest)
			panic("leftover data")
		}
		if !fuzz.DeepEqual(v, v1) {
			fmt.Printf("v0: %#v\n", reflect.ValueOf(v).Elem().Interface())
			fmt.Printf("v1: %#v\n", reflect.ValueOf(v1).Elem().Interface())
			panic(fmt.Sprintf("not equal %T", x))
		}
	}
	return score
}
コード例 #19
0
ファイル: Marshal.go プロジェクト: cwen-coder/goTrain
func main() {
	mdata, err := asn1.Marshal(13)
	checkError(err)
	var n int
	_, err1 := asn1.Unmarshal(mdata, &n)
	checkError(err1)
	fmt.Println("After marshal/unmarshal:", n)

	t := time.Now()
	m, err := asn1.Marshal(t)
	var newtime = new(time.Time)
	_, err = asn1.Unmarshal(m, newtime)
	checkError(err)
	fmt.Println(newtime)
}
コード例 #20
0
ファイル: asn1.go プロジェクト: j4ustin/go-ethereum
// Decode a DER-encoded public key.
func UnmarshalPublic(in []byte) (pub *PublicKey, err error) {
	var subj asnSubjectPublicKeyInfo

	if _, err = asn1.Unmarshal(in, &subj); err != nil {
		return
	}
	if !subj.Algorithm.Equal(idEcPublicKeySupplemented) {
		err = ErrInvalidPublicKey
		return
	}
	pub = new(PublicKey)
	pub.Curve = namedCurveFromOID(subj.Supplements.ECDomain)
	x, y := elliptic.Unmarshal(pub.Curve, subj.PublicKey.Bytes)
	if x == nil {
		err = ErrInvalidPublicKey
		return
	}
	pub.X = x
	pub.Y = y
	pub.Params = new(ECIESParams)
	asnECIEStoParams(subj.Supplements.ECCAlgorithms.ECIES, pub.Params)
	asnECDHtoParams(subj.Supplements.ECCAlgorithms.ECDH, pub.Params)
	if pub.Params == nil {
		if pub.Params = ParamsFromCurve(pub.Curve); pub.Params == nil {
			err = ErrInvalidPublicKey
		}
	}
	return
}
コード例 #21
0
ファイル: asn1.go プロジェクト: j4ustin/go-ethereum
// Decode a private key from a DER-encoded format.
func UnmarshalPrivate(in []byte) (prv *PrivateKey, err error) {
	var ecprv asnPrivateKey

	if _, err = asn1.Unmarshal(in, &ecprv); err != nil {
		return
	} else if ecprv.Version != asnECPrivKeyVer1 {
		err = ErrInvalidPrivateKey
		return
	}

	privateCurve := namedCurveFromOID(ecprv.Curve)
	if privateCurve == nil {
		err = ErrInvalidPrivateKey
		return
	}

	prv = new(PrivateKey)
	prv.D = new(big.Int).SetBytes(ecprv.Private)

	if pub, err := UnmarshalPublic(ecprv.Public.Bytes); err != nil {
		return nil, err
	} else {
		prv.PublicKey = *pub
	}

	return
}
コード例 #22
0
func getPermittedMethods(cert *x509.Certificate) (map[string]struct{}, error) {
	methodList := make(map[string]struct{})
	for _, extension := range cert.Extensions {
		if extension.Id.String() != constants.PermittedMethodListOID {
			continue
		}
		var lines []string
		rest, err := asn1.Unmarshal(extension.Value, &lines)
		if err != nil {
			return nil, err
		}
		if len(rest) > 0 {
			return nil, fmt.Errorf("%d extra bytes in method extension",
				len(rest))
		}
		for _, sm := range lines {
			if strings.Count(sm, ".") == 1 {
				methodList[sm] = struct{}{}
			} else {
				return nil, fmt.Errorf("bad line: \"%s\"", sm)
			}
		}
		return methodList, nil
	}
	return methodList, nil
}
コード例 #23
0
ファイル: security.go プロジェクト: mgenov/snmpgo
func decrypt(msg *messageV3, proto PrivProtocol, key, privParam []byte) (err error) {
	var raw asn1.RawValue
	_, err = asn1.Unmarshal(msg.PduBytes(), &raw)
	if err != nil {
		return
	}
	if raw.Class != classUniversal || raw.Tag != tagOctetString || raw.IsCompound {
		return asn1.StructuralError{fmt.Sprintf(
			"Invalid encrypted Pdu object - Class [%02x], Tag [%02x] : [%s]",
			raw.Class, raw.Tag, toHexStr(msg.PduBytes(), " "))}
	}

	var dst []byte
	switch proto {
	case Des:
		dst, err = decryptDES(raw.Bytes, key, privParam)
	case Aes:
		dst, err = decryptAES(
			raw.Bytes, key, privParam, int32(msg.AuthEngineBoots), int32(msg.AuthEngineTime))
	}

	if err == nil {
		msg.SetPduBytes(dst)
	}
	return
}
コード例 #24
0
ファイル: pdu.go プロジェクト: yulianghsueh/snmpgo
func (v *VarBind) 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 VarBind object - Class [%02x], Tag [%02x] : [%s]",
			raw.Class, raw.Tag, toHexStr(b, " "))}
	}

	var oid Oid
	next, err := (&oid).Unmarshal(raw.Bytes)
	if err != nil {
		return
	}

	variable, _, err := unmarshalVariable(next)
	if err != nil {
		return
	}

	v.Oid = &oid
	v.Variable = variable
	return
}
コード例 #25
0
ファイル: keys.go プロジェクト: CadeLaRen/docker-3
// Sign creates an ecdsa signature
func (k ECDSAPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
	ecdsaPrivKey, ok := k.CryptoSigner().(*ecdsa.PrivateKey)
	if !ok {
		return nil, errors.New("Signer was based on the wrong key type")
	}
	hashed := sha256.Sum256(msg)
	sigASN1, err := ecdsaPrivKey.Sign(rand, hashed[:], opts)
	if err != nil {
		return nil, err
	}

	sig := ecdsaSig{}
	_, err = asn1.Unmarshal(sigASN1, &sig)
	if err != nil {
		return nil, err
	}
	rBytes, sBytes := sig.R.Bytes(), sig.S.Bytes()
	octetLength := (ecdsaPrivKey.Params().BitSize + 7) >> 3

	// MUST include leading zeros in the output
	rBuf := make([]byte, octetLength-len(rBytes), octetLength)
	sBuf := make([]byte, octetLength-len(sBytes), octetLength)

	rBuf = append(rBuf, rBytes...)
	sBuf = append(sBuf, sBytes...)
	return append(rBuf, sBuf...), nil
}
コード例 #26
0
ファイル: types.go プロジェクト: JonathanLogan/mute
// Unmarshal CacheData
func (cd *CacheData) Unmarshal(d string) (*CacheData, error) {
	if cd == nil {
		cd = new(CacheData)
	}
	if cd.VerifyKeys == nil {
		cd.VerifyKeys = make([][ed25519.PublicKeySize]byte, 0)
	}
	db64, err := base64.StdEncoding.DecodeString(d)
	if err != nil {
		return nil, err
	}
	cdb := new(CacheDataDB)
	_, err = asn1.Unmarshal(db64, cdb)
	if err != nil {
		return nil, err
	}
	for _, key := range cdb.VerifyKeys {
		copyKey := new([ed25519.PublicKeySize]byte)
		copy(copyKey[:], key)
		cd.VerifyKeys = append(cd.VerifyKeys, *copyKey)
	}
	cd.AuthToken = cdb.AuthToken
	cd.AuthTries = cdb.AuthTries
	return cd, nil
}
コード例 #27
0
ファイル: ocsp.go プロジェクト: spazbite187/snatchtls
// ParseRequest parses an OCSP request in DER form. It only supports
// requests for a single certificate. Signed requests are not supported.
// If a request includes a signature, it will result in a ParseError.
func ParseRequest(bytes []byte) (*Request, error) {
	var req ocspRequest
	rest, err := asn1.Unmarshal(bytes, &req)
	if err != nil {
		return nil, err
	}
	if len(rest) > 0 {
		return nil, ParseError("trailing data in OCSP request")
	}

	if len(req.TBSRequest.RequestList) == 0 {
		return nil, ParseError("OCSP request contains no request body")
	}
	innerRequest := req.TBSRequest.RequestList[0]

	hashFunc := getHashAlgorithmFromOID(innerRequest.Cert.HashAlgorithm.Algorithm)
	if hashFunc == crypto.Hash(0) {
		return nil, ParseError("OCSP request uses unknown hash function")
	}

	return &Request{
		HashAlgorithm:  hashFunc,
		IssuerNameHash: innerRequest.Cert.NameHash,
		IssuerKeyHash:  innerRequest.Cert.IssuerKeyHash,
		SerialNumber:   innerRequest.Cert.SerialNumber,
	}, nil
}
コード例 #28
0
ファイル: objects.go プロジェクト: rf152/boulder
// CheckSignature validates that the returned SCT signature is a valid SHA256 +
// ECDSA signature but does not verify that a specific public key signed it.
func (sct *SignedCertificateTimestamp) CheckSignature() error {
	if len(sct.Signature) < 4 {
		return errors.New("SCT signature is truncated")
	}
	// Since all of the known logs currently only use SHA256 hashes and ECDSA
	// keys, only allow those
	if sct.Signature[0] != sctHashSHA256 {
		return fmt.Errorf("Unsupported SCT hash function [%d]", sct.Signature[0])
	}
	if sct.Signature[1] != sctSigECDSA {
		return fmt.Errorf("Unsupported SCT signature algorithm [%d]", sct.Signature[1])
	}

	var ecdsaSig struct {
		R, S *big.Int
	}
	// Ignore the two length bytes and attempt to unmarshal the signature directly
	signatureBytes := sct.Signature[4:]
	signatureBytes, err := asn1.Unmarshal(signatureBytes, &ecdsaSig)
	if err != nil {
		return fmt.Errorf("Failed to parse SCT signature, %s", err)
	}
	if len(signatureBytes) > 0 {
		return fmt.Errorf("Trailing garbage after signature")
	}

	return nil
}
コード例 #29
0
ファイル: pkcs7.go プロジェクト: GauntletWizard/vault
// Parse decodes a DER encoded PKCS7 package
func Parse(data []byte) (p7 *PKCS7, err error) {
	if len(data) == 0 {
		return nil, errors.New("pkcs7: input data is empty")
	}
	var info contentInfo
	der, err := ber2der(data)
	if err != nil {
		return nil, err
	}
	rest, err := asn1.Unmarshal(der, &info)
	if len(rest) > 0 {
		err = asn1.SyntaxError{Msg: "trailing data"}
		return
	}
	if err != nil {
		return
	}

	// fmt.Printf("--> Content Type: %s", info.ContentType)
	switch {
	case info.ContentType.Equal(oidSignedData):
		return parseSignedData(info.Content.Bytes)
	case info.ContentType.Equal(oidEnvelopedData):
		return parseEnvelopedData(info.Content.Bytes)
	}
	return nil, ErrUnsupportedContentType
}
コード例 #30
0
ファイル: message.go プロジェクト: mgenov/snmpgo
func (sec *securityParameterV3) Unmarshal(b []byte) (rest []byte, err error) {
	var raw asn1.RawValue
	rest, err = asn1.Unmarshal(b, &raw)
	if err != nil {
		return
	}

	if raw.Class != classUniversal || raw.Tag != tagOctetString || raw.IsCompound {
		return nil, asn1.StructuralError{fmt.Sprintf(
			"Invalid SecurityParameter object - Class [%02x], Tag [%02x] : [%s]",
			raw.Class, raw.Tag, toHexStr(b, " "))}
	}

	_, err = asn1.Unmarshal(raw.Bytes, sec)
	return
}