Example #1
0
func (attrs *attributes) ForMarshaling() ([]attribute, error) {
	sortables := make(attributeSet, len(attrs.types))
	for i := range sortables {
		attrType := attrs.types[i]
		attrValue := attrs.values[i]
		asn1Value, err := asn1.Marshal(attrValue)
		if err != nil {
			return nil, err
		}
		attr := attribute{
			Type:  attrType,
			Value: asn1.RawValue{Tag: 17, IsCompound: true, Bytes: asn1Value}, // 17 == SET tag
		}
		encoded, err := asn1.Marshal(attr)
		if err != nil {
			return nil, err
		}
		sortables[i] = sortableAttribute{
			SortKey:   encoded,
			Attribute: attr,
		}
	}
	sort.Sort(sortables)
	return sortables.Attributes(), nil
}
Example #2
0
// MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
	var pubBytes []byte

	switch pub := pub.(type) {
	case *rsa.PublicKey:
		pubBytes, _ = asn1.Marshal(rsaPublicKey{
			N: pub.N,
			E: pub.E,
		})
	default:
		return nil, errors.New("MarshalPKIXPublicKey: unknown public key type")
	}

	pkix := pkixPublicKey{
		Algo: pkix.AlgorithmIdentifier{
			Algorithm: []int{1, 2, 840, 113549, 1, 1, 1},
			// This is a NULL parameters value which is technically
			// superfluous, but most other code includes it and, by
			// doing this, we match their public key hashes.
			Parameters: asn1.RawValue{
				Tag: 5,
			},
		},
		BitString: asn1.BitString{
			Bytes:     pubBytes,
			BitLength: 8 * len(pubBytes),
		},
	}

	ret, _ := asn1.Marshal(pkix)
	return ret, nil
}
Example #3
0
func makeSafeContents (bags []safeBag, password []byte, alg String) (ci []contentInfo, err error) {
	ci = make([]contentInfo, 2)
	for i, b := range bags {
		switch b.ID {
		case oidCertTypeX509Certificate:
			
			ci[i].ContentType = oidDataContentType
			ci[i].Content, err = asn1.Marshal(b)
			if err != nil{
				return nil, err
			}
		
		case oidPkcs8ShroudedKeyBagType
			ci[i].Content, err = pbEncrypt(b, alg, password)
			if err != nil{
				return nil, err
			}

			ci[i].Content, err = asn1.Marshal(ki.Content)
			if err != nil{
				return nil, err
			}
		}
	}
	return ci, err
}
Example #4
0
File: x509.go Project: ArtemL/GCC
func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
	switch pub := pub.(type) {
	case *rsa.PublicKey:
		publicKeyBytes, err = asn1.Marshal(rsaPublicKey{
			N: pub.N,
			E: pub.E,
		})
		publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
		// This is a NULL parameters value which is technically
		// superfluous, but most other code includes it and, by
		// doing this, we match their public key hashes.
		publicKeyAlgorithm.Parameters = asn1.RawValue{
			Tag: 5,
		}
	case *ecdsa.PublicKey:
		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
		oid, ok := oidFromNamedCurve(pub.Curve)
		if !ok {
			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
		}
		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
		var paramBytes []byte
		paramBytes, err = asn1.Marshal(oid)
		if err != nil {
			return
		}
		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
	default:
		return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA public keys supported")
	}

	return publicKeyBytes, publicKeyAlgorithm, nil
}
Example #5
0
func (msg *messageV3) Marshal() (b []byte, err error) {
	var buf []byte
	raw := asn1.RawValue{Class: classUniversal, Tag: tagSequence, IsCompound: true}

	buf, err = asn1.Marshal(msg.version)
	if err != nil {
		return
	}
	raw.Bytes = buf

	buf, err = msg.globalDataV3.Marshal()
	if err != nil {
		return
	}
	raw.Bytes = append(raw.Bytes, buf...)

	buf, err = msg.securityParameterV3.Marshal()
	if err != nil {
		return
	}
	raw.Bytes = append(raw.Bytes, buf...)

	raw.Bytes = append(raw.Bytes, msg.pduBytes...)
	return asn1.Marshal(raw)
}
Example #6
0
func Encode(utf8Password []byte, privateKey interface{}, certificate x509.Certificate,
			algorithm String) (p12Data, err error){
	password, err := bmpString(utf8Password)
	if err != nil {
		return nil, err
	}

	bags = make([]safeBag, 2)
	bags[0] = encodePkcs8ShroudedBag(privateKey, password, algorithm)
	bags[1] = encodeCertBag(certificate)

	content = make([]contentInfo, 2)
	content = makeSafeContents(bags, password, keyEncr, algorithm)

	pfx = new(pfxPdu)

	// Should this be pfx.AuthSafe.Content.Bytes ?
	pfx.AuthSafe.Content, err = asn1.Marshal(content)
	if err != nil {
		return nil, err
	}

	// Only version supported by the read package.
	pfx.Version = 3

	// Should Macdata be a parameter of the function?
	pfx.Macdata = ?

	p12Data, err = asn1.Marshal(pfx)
	if err != nil{
		return nil, err
	}
	return
}
Example #7
0
func encodePkcs8ShroudedKeyBag(privateKey interface{}, password []byte) (asn1Data []byte, err error) {
	var pkData []byte
	if pkData, err = marshalPKCS8PrivateKey(privateKey); err != nil {
		return nil, errors.New("pkcs12: error encoding PKCS#8 private key: " + err.Error())
	}

	randomSalt := make([]byte, 8)
	if _, err = rand.Read(randomSalt); err != nil {
		return nil, errors.New("pkcs12: error reading random salt: " + err.Error())
	}
	var paramBytes []byte
	if paramBytes, err = asn1.Marshal(pbeParams{Salt: randomSalt, Iterations: 2048}); err != nil {
		return nil, errors.New("pkcs12: error encoding params: " + err.Error())
	}

	var pkinfo encryptedPrivateKeyInfo
	pkinfo.AlgorithmIdentifier.Algorithm = oidPBEWithSHAAnd3KeyTripleDESCBC
	pkinfo.AlgorithmIdentifier.Parameters.FullBytes = paramBytes

	if err = pbEncrypt(&pkinfo, pkData, password); err != nil {
		return nil, errors.New("pkcs12: error encrypting PKCS#8 shrouded key bag: " + err.Error())
	}

	if asn1Data, err = asn1.Marshal(pkinfo); err != nil {
		return nil, errors.New("pkcs12: error encoding PKCS#8 shrouded key bag: " + err.Error())
	}

	return asn1Data, nil
}
Example #8
0
func marshalPKCS8PrivateKey(key interface{}) (der []byte, err error) {
	var privKey pkcs8
	switch key := key.(type) {
	case *rsa.PrivateKey:
		privKey.Algo.Algorithm = oidPublicKeyRSA
		// This is a NULL parameters value which is technically
		// superfluous, but most other code includes it.
		privKey.Algo.Parameters = asn1.RawValue{
			Tag: 5,
		}
		privKey.PrivateKey = x509.MarshalPKCS1PrivateKey(key)
	case *ecdsa.PrivateKey:
		privKey.Algo.Algorithm = oidPublicKeyECDSA
		namedCurveOID, ok := oidFromNamedCurve(key.Curve)
		if !ok {
			return nil, errors.New("pkcs12: unknown elliptic curve")
		}
		if privKey.Algo.Parameters.FullBytes, err = asn1.Marshal(namedCurveOID); err != nil {
			return nil, errors.New("pkcs12: failed to embed OID of named curve in PKCS#8: " + err.Error())
		}
		if privKey.PrivateKey, err = x509.MarshalECPrivateKey(key); err != nil {
			return nil, errors.New("pkcs12: failed to embed EC private key in PKCS#8: " + err.Error())
		}
	default:
		return nil, errors.New("pkcs12: only RSA and ECDSA private keys supported")
	}
	return asn1.Marshal(privKey)
}
Example #9
0
// Sign generate sign for data with cert & private key
func Sign(data io.Reader, cert *x509.Certificate, priv *rsa.PrivateKey) ([]byte, error) {
	var hash = sha1.New()
	if _, err := io.Copy(hash, data); err != nil {
		return nil, err
	}
	var signedData = signedData{
		Version: 1,
		DigestAlgorithms: []algorithmIdentifier{{
			Algorithm:  oidSHA1,
			Parameters: asn1.RawValue{Tag: 5},
		}},
		ContentInfo: contentInfo{Type: oidPKCS7Data},
		Certificates: asn1.RawValue{
			Class: 2, Tag: 0, Bytes: append(wwdr, cert.Raw...), IsCompound: true,
		},
		SignerInfos: []signerInfo{{
			Version: 1,
			IssuerAndSerialNumber: issuerAndSerialNumber{
				Issuer:       asn1.RawValue{FullBytes: cert.RawIssuer},
				SerialNumber: cert.SerialNumber,
			},
			DigestAlgorithm: algorithmIdentifier{
				Algorithm:  oidSHA1,
				Parameters: asn1.RawValue{Tag: 5},
			},
			AuthenticatedAttributes: []attribute{
				newAttribute(oidPKCS9ContentType, oidPKCS7Data),
				newAttribute(oidPKCS9SigningTime, time.Now().UTC()),
				newAttribute(oidPKCS9MessageDigest, hash.Sum(nil)),
			},
			DigestEncryptionAlgorithm: algorithmIdentifier{
				Algorithm:  oidPKCS1RSAEncryption,
				Parameters: asn1.RawValue{Tag: 5},
			},
		}},
	}
	encodedAuthenticatedAttributes, err := asn1.Marshal(
		signedData.SignerInfos[0].AuthenticatedAttributes)
	if err != nil {
		return nil, err
	}
	// For the digest of the authenticated attributes, we need a
	// slightly different encoding.  Change the attributes from a
	// SEQUENCE to a SET.
	var originalFirstByte = encodedAuthenticatedAttributes[0]
	encodedAuthenticatedAttributes[0] = 0x31
	hash = sha1.New()
	hash.Write(encodedAuthenticatedAttributes)
	var attributesDigest = hash.Sum(nil)
	encodedAuthenticatedAttributes[0] = originalFirstByte
	encryptedDigest, err := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA1, attributesDigest)
	if err != nil {
		return nil, err
	}
	signedData.SignerInfos[0].EncryptedDigest = encryptedDigest
	return asn1.Marshal(container{
		OID:        oidPKCS7SignedData,
		SignedData: signedData,
	})
}
Example #10
0
// marshalPKCS8PrivateKey marshals the provided ECDSA private key into the
// PKCS#8 private key format.
func marshalPKCS8PrivateKey(key *ecdsa.PrivateKey) ([]byte, error) {
	oid, ok := oidFromNamedCurve(key.PublicKey.Curve)
	if !ok {
		return nil, fmt.Errorf("illegal curve")
	}
	paramBytes, err := asn1.Marshal(oid)
	if err != nil {
		return nil, err
	}
	var algo pkix.AlgorithmIdentifier
	algo.Algorithm = oidPublicKeyECDSA
	algo.Parameters.FullBytes = paramBytes

	privBytes, err := x509.MarshalECPrivateKey(key)
	if err != nil {
		return nil, err
	}
	pkcs8 := struct {
		Version    int
		Algo       pkix.AlgorithmIdentifier
		PrivateKey []byte
	}{
		Version:    1,
		Algo:       algo,
		PrivateKey: privBytes,
	}
	return asn1.Marshal(pkcs8)
}
Example #11
0
func (sec *securityParameterV3) Marshal() ([]byte, error) {
	raw := asn1.RawValue{Class: classUniversal, Tag: tagOctetString, IsCompound: false}

	buf, err := asn1.Marshal(*sec)
	if err != nil {
		return nil, err
	}
	raw.Bytes = buf

	return asn1.Marshal(raw)
}
Example #12
0
// Finish marshals the content and its signers
func (sd *SignedData) Finish() ([]byte, error) {
	sd.sd.Certificates = marshalCertificates(sd.certs)
	inner, err := asn1.Marshal(sd.sd)
	if err != nil {
		return nil, err
	}
	outer := contentInfo{
		ContentType: oidSignedData,
		Content:     asn1.RawValue{Class: 2, Tag: 0, Bytes: inner, IsCompound: true},
	}
	return asn1.Marshal(outer)
}
Example #13
0
// Encrypt signs the message with the private key, and encrypts it to
// the certificate supplied.
func Encrypt(priv *rsa.PrivateKey, cert *x509.Certificate, msg []byte) ([]byte, bool) {
	var pub *rsa.PublicKey
	switch certPub := cert.PublicKey.(type) {
	case *rsa.PublicKey:
		pub = certPub
	default:
		return nil, false
	}

	var signed = signature{msg, nil}

	h := sha256.New()
	h.Write(msg)

	var err error
	signed.Signature, err = rsa.SignPSS(rand.Reader, priv, crypto.SHA256,
		h.Sum(nil), nil)
	if err != nil {
		return nil, false
	}

	out, err := asn1.Marshal(signed)
	if err != nil {
		return nil, false
	}

	key := aesgcm.NewKey()
	if key == nil {
		return nil, false
	}

	out, ok := aesgcm.Encrypt(key, out)
	if !ok {
		return nil, false
	}

	var message message
	message.Signed = out

	h.Reset()
	message.Key, err = rsa.EncryptOAEP(h, rand.Reader, pub, key, nil)
	if err != nil {
		return nil, false
	}

	out, err = asn1.Marshal(message)
	if err != nil {
		return nil, false
	}

	return out, true
}
Example #14
0
func CreateCertificateRequest(rand io.Reader, csr *CertificationRequest, pub interface{}, priv interface{}) ([]byte, error) {
	rsaPub, ok := pub.(*rsa.PublicKey)
	if !ok {
		return nil, errors.New("pkcs10: non-RSA public keys not supported")
	}

	rsaPriv, ok := priv.(*rsa.PrivateKey)
	if !ok {
		return nil, errors.New("x509: non-RSA private keys not supported")
	}

	if rsaPriv != nil {
	}

	asn1PublicKey, err := asn1.Marshal(rsaPublicKey{
		N: rsaPub.N,
		E: rsaPub.E,
	})
	if err != nil {
		return nil, err
	}

	encodedPublicKey := asn1.BitString{BitLength: len(asn1PublicKey) * 8, Bytes: asn1PublicKey}

	var p pkcs10
	p.Info.Subject = csr.Subject.ToRDNSequence()
	p.Info.Version = csr.Version
	p.Info.SubjectInfo.Algorithm = pkix.AlgorithmIdentifier{Algorithm: oidPublicKeyRsa}
	p.Info.SubjectInfo.PublicKey = encodedPublicKey
	p.Info.Attributes = asn1.RawValue{Class: 2, Tag: 0, IsCompound: true, FullBytes: []byte{160, 0}}

	pkcsInfoContents, err := asn1.Marshal(p.Info)
	if err != nil {
		return nil, err
	}

	h := sha1.New()
	h.Write(pkcsInfoContents)
	digest := h.Sum(nil)

	signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
	if err != nil {
		return nil, err
	}

	p.Algo = pkix.AlgorithmIdentifier{Algorithm: oidSignatureSHA1WithRSA}
	p.Sig = asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}

	return asn1.Marshal(p)
}
Example #15
0
func newECDSACertificateRequest(priv *ecdsa.PrivateKey, si *SubjectInfo) (out []byte, err error) {
	var siAttr rdnSequence

	rdnAppendPrintable(si.Country, asn1CountryName, &siAttr)
	rdnAppendPrintable(si.StateOrProvince, asn1StateOrProvName, &siAttr)
	rdnAppendPrintable(si.Locality, asn1LocalityName, &siAttr)
	rdnAppendPrintable(si.OrgName, asn1OrgName, &siAttr)
	rdnAppendPrintable(si.OrgUnitName, asn1OrgUnitName, &siAttr)
	rdnAppendPrintable(si.CommonName, asn1CommonName, &siAttr)
	rdnAppendPrintable(si.Email, asn1EmailAddress, &siAttr)

	pkInfo, err := encodeECDSA(priv.PublicKey)
	if err != nil {
		return
	}
	var csrInfo = certificateRequestInfo{
		Subject: siAttr,
		PKInfo:  pkInfo,
	}

	sigData, err := asn1.Marshal(csrInfo)
	if err != nil {
		return
	}
	sum := sha256.Sum256(sigData)
	r, s, err := ecdsa.Sign(rand.Reader, priv, sum[:])
	if err != nil {
		return
	}
	ecdsaSig := ecdsaSignature{r, s}
	sig, err := asn1.Marshal(ecdsaSig)
	if err != nil {
		return
	}

	var crt = certificateRequest{
		Info:      csrInfo,
		SigAlgo:   nullAlgorithm(asn1SHA256withECDSA),
		Signature: toBitString(sig),
	}

	var block pem.Block
	block.Type = "CERTIFICATE REQUEST"
	block.Bytes, err = asn1.Marshal(crt)
	if err != nil {
		return
	}
	out = pem.EncodeToMemory(&block)
	return
}
Example #16
0
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)
}
Example #17
0
// Encode a private key to DER format.
func MarshalPrivate(prv *PrivateKey) ([]byte, error) {
	ecprv, err := marshalPrivateKey(prv)
	if err != nil {
		return nil, err
	}
	return asn1.Marshal(ecprv)
}
Example #18
0
func TestPbDecrypterFor(t *testing.T) {
	params, _ := asn1.Marshal(pbeParams{
		Salt:       []byte{1, 2, 3, 4, 5, 6, 7, 8},
		Iterations: 2048,
	})
	alg := pkix.AlgorithmIdentifier{
		Algorithm: asn1.ObjectIdentifier([]int{1, 2, 3}),
		Parameters: asn1.RawValue{
			FullBytes: params,
		},
	}

	pass, _ := bmpString([]byte("Sesame open"))

	_, err := pbDecrypterFor(alg, pass)
	if _, ok := err.(NotImplementedError); !ok {
		t.Errorf("expected not implemented error, got: %T %s", err, err)
	}

	alg.Algorithm = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3})
	cbc, err := pbDecrypterFor(alg, pass)
	if err != nil {
		t.Errorf("err: %v", err)
	}

	M := []byte{1, 2, 3, 4, 5, 6, 7, 8}
	expectedM := []byte{185, 73, 135, 249, 137, 1, 122, 247}
	cbc.CryptBlocks(M, M)

	if bytes.Compare(M, expectedM) != 0 {
		t.Errorf("expected M to be '%d', but found '%d", expectedM, M)
	}
}
Example #19
0
// Encode a public key to DER format.
func MarshalPublic(pub *PublicKey) ([]byte, error) {
	subj, err := marshalSubjectPublicKeyInfo(pub)
	if err != nil {
		return nil, err
	}
	return asn1.Marshal(subj)
}
Example #20
0
func makeParcel(visible bool, serial int64, ca *Parcel, host string) (p *Parcel, err error) {
	ser := big.NewInt(serial)
	cert := makeCertTemplate(
		false,
		host,
		ca.Certificate.Subject.CommonName,
		ser)
	key := keyBarrel.GetKey()
	hasher := sha1.New()
	bytes, err := asn1.Marshal(key.PublicKey)
	hasher.Write(bytes)
	h := hasher.Sum(nil)
	cert.SubjectKeyId = h
	cert.AuthorityKeyId = ca.Certificate.SubjectKeyId

	raw, err := x509.CreateCertificate(rand.Reader, cert, ca.Certificate, &key.PublicKey, ca.PrivateKey)
	if err != nil {
		return
	}

	p = &Parcel{
		Visible:             visible,
		Certificate:         cert,
		PrivateKey:          key,
		DERCertificateBytes: raw,
	}
	return
}
Example #21
0
// MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
	key.Precompute()

	version := 0
	if len(key.Primes) > 2 {
		version = 1
	}

	priv := pkcs1PrivateKey{
		Version: version,
		N:       key.N,
		E:       key.PublicKey.E,
		D:       key.D,
		P:       key.Primes[0],
		Q:       key.Primes[1],
		Dp:      key.Precomputed.Dp,
		Dq:      key.Precomputed.Dq,
		Qinv:    key.Precomputed.Qinv,
	}

	priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
	for i, values := range key.Precomputed.CRTValues {
		priv.AdditionalPrimes[i].Prime = key.Primes[2+i]
		priv.AdditionalPrimes[i].Exp = values.Exp
		priv.AdditionalPrimes[i].Coeff = values.Coeff
	}

	b, _ := asn1.Marshal(priv)
	return b
}
Example #22
0
// marshalECDSASignature returns the ASN.1 encoding of the provided ECDSA signature.
func marshalECDSASignature(s security.Signature) ([]byte, error) {
	sig := &ecdsaSignature{
		R: new(big.Int).SetBytes(s.R),
		S: new(big.Int).SetBytes(s.S),
	}
	return asn1.Marshal(sig)
}
func MarshalStruct() {
	t := thinger{
		"Foo",
		123,
		1234.5678,
		time.Now(),
		map[string]string{"hello": "world"},
		[]string{"one", "two", "three"},
	}

	j, _ := json.Marshal(t)
	c, _ := cbor.Marshal(t)
	a, err := asn1.Marshal(t)
	if err != nil {
		fmt.Printf("error: %s\n", err)
	}

	w := tabwriter.NewWriter(os.Stdout, 20, 4, 1, ' ', 0)
	fmt.Fprintln(w, "Encoding\tSize\tGraph")
	tpl := "%s\t%d\t%s\n"

	fmt.Fprintf(w, tpl, "JSON", len(j), strings.Repeat("#", len(j)))
	fmt.Fprintf(w, tpl, "ASN.1", len(a), strings.Repeat("#", len(a)))
	fmt.Fprintf(w, tpl, "CBOR", len(c), strings.Repeat("#", len(c)))
	w.Flush()
}
Example #24
0
func subjectBytes(cert *Certificate) ([]byte, error) {
	if len(cert.RawSubject) > 0 {
		return cert.RawSubject, nil
	}

	return asn1.Marshal(cert.Subject.ToRDNSequence())
}
Example #25
0
// SerializeSCTList serializes the passed-in slice of SignedCertificateTimestamp into a
// byte slice as a SignedCertificateTimestampList (see RFC6962 Section 3.3)
func SerializeSCTList(scts []SignedCertificateTimestamp) ([]byte, error) {
	size, err := SCTListSerializedLength(scts)
	if err != nil {
		return nil, err
	}
	fullSize := 2 + size // 2 bytes for length + size of SCT list
	if fullSize > MaxSCTListLength {
		return nil, fmt.Errorf("SCT List too large to serialize: %d", fullSize)
	}
	buf := new(bytes.Buffer)
	buf.Grow(fullSize)
	if err = writeUint(buf, uint64(size), 2); err != nil {
		return nil, err
	}
	for _, sct := range scts {
		serialized, err := SerializeSCT(sct)
		if err != nil {
			return nil, err
		}
		if err = writeVarBytes(buf, serialized, 2); err != nil {
			return nil, err
		}
	}
	return asn1.Marshal(buf.Bytes()) // transform to Octet String
}
Example #26
0
// marshalPKCS8PrivateKey converts a private key to PKCS#8 encoded form.
// See http://www.rsa.com/rsalabs/node.asp?id=2130 and RFC5208.
func marshalPKCS8PrivateKey(key interface{}) (der []byte, err error) {
	pkcs := pkcs8{
		Version: 0,
	}

	switch key := key.(type) {
	case *rsa.PrivateKey:
		pkcs.Algo = pkix.AlgorithmIdentifier{
			Algorithm:  oidPublicKeyRSA,
			Parameters: nullAsn,
		}
		pkcs.PrivateKey = x509.MarshalPKCS1PrivateKey(key)
	case *ecdsa.PrivateKey:
		bytes, err := x509.MarshalECPrivateKey(key)
		if err != nil {
			return nil, errors.New("x509: failed to marshal to PKCS#8: " + err.Error())
		}

		pkcs.Algo = pkix.AlgorithmIdentifier{
			Algorithm:  oidPublicKeyECDSA,
			Parameters: nullAsn,
		}
		pkcs.PrivateKey = bytes
	default:
		return nil, errors.New("x509: PKCS#8 only RSA and ECDSA private keys supported")
	}

	bytes, err := asn1.Marshal(pkcs)
	if err != nil {
		return nil, errors.New("x509: failed to marshal to PKCS#8: " + err.Error())
	}

	return bytes, nil
}
Example #27
0
// EXP_ExecuteWithBinding executes a transaction with a specific binding/TXHandler
func (d *Devops) EXP_ExecuteWithBinding(ctx context.Context, executeWithBinding *pb.ExecuteWithBinding) (*pb.Response, error) {

	if d.isSecurityEnabled {
		devopsLogger.Debug("Getting TxHandler for binding")

		txHandler, err := d.bindingMap.getTxHandlerForBinding(executeWithBinding.Binding)

		if nil != err {
			return &pb.Response{Status: pb.Response_FAILURE, Msg: []byte(err.Error())}, nil
		}

		ctorbytes, merr := asn1.Marshal(*executeWithBinding.ChaincodeInvocationSpec.ChaincodeSpec.CtorMsg)
		if merr != nil {
			return nil, fmt.Errorf("Error marshalling constructor: %s", err)
		}
		tid, generr := util.GenerateIDWithAlg("", ctorbytes)
		if generr != nil {
			return nil, fmt.Errorf("Error: cannot generate TX ID (executing with binding)")
		}

		tx, err := txHandler.NewChaincodeExecute(executeWithBinding.ChaincodeInvocationSpec, tid)
		if err != nil {
			return nil, fmt.Errorf("Error creating executing with binding:  %s", err)
		}

		return d.coord.ExecuteTransaction(tx), nil
		//return &pb.Response{Status: pb.Response_FAILURE, Msg: []byte("NOT IMPLEMENTED")}, nil

		//return &pb.Response{Status: pb.Response_SUCCESS, Msg: sigmaOutputBytes}, nil
	}
	devopsLogger.Warning("Security NOT enabled")
	return &pb.Response{Status: pb.Response_FAILURE, Msg: []byte("Security NOT enabled")}, nil
}
Example #28
0
func TestPacketSizes(t *testing.T) {
	asnPacket := packet{
		testRawPacket.Timestamp,
		testRawPacket.Counter,
		testRawPacket.Chunk[:],
	}
	packet, err := asn1.Marshal(asnPacket)
	checkError(t, err)

	jpacket, err := json.Marshal(asnPacket)
	checkError(t, err)

	jout, err := crypt.Encrypt(jpacket, testPub, signer)
	checkError(t, err)

	buf := &bytes.Buffer{}
	enc := gob.NewEncoder(buf)
	err = enc.Encode(asnPacket)
	checkError(t, err)
	gpacket := buf.Bytes()

	gout, err := crypt.Encrypt(gpacket, testPub, signer)
	checkError(t, err)

	fmt.Println("              ASN.1 packet length:", len(packet))
	fmt.Println("               JSON packet length:", len(jpacket))
	fmt.Println("                Gob packet length:", len(gpacket))
	fmt.Println("Signed and encrypted ASN.1 length:", len(testPacket))
	fmt.Println(" Signed and encrypted JSON length:", len(jout))
	fmt.Println("  Signed and encrypted gob length:", len(gout))
}
Example #29
0
// NewCertficationPolicy creates an x509 certificate extension detailing a
// certification policy, including a statement and a user notice. The resulting
// extension can be added to x509.Certficate.ExtraExtensions.
func NewCertficationPolicy(cps, unotice string) (pkix.Extension, error) {
	pi := []policyInformation{
		policyInformation{
			PolicyIdentifier: idSubjectIdentityValidated,
			PolicyQualifiers: []interface{}{
				policyQualifierInfo{
					PolicyQualifierId: idQtCertificationPracticeStatement,
					Qualifier:         cps,
				},
				policyQualifierInfoSequence{
					PolicyQualifierId: idQtUnotice,
					Qualifier:         []string{unotice},
				},
			},
		},
	}
	asn1Bytes, err := asn1.Marshal(pi)
	if err != nil {
		return pkix.Extension{}, err
	}
	// Hack: Change the string tag for unotice from IA5 to VisibleString. The
	// last part of asn1Bytes should be the IA5 tag, a length byte, and the
	// unotice string.
	i := len(asn1Bytes) - len(unotice)
	if i < 2 || (int)(asn1Bytes[i-1]) != len(unotice) || asn1Bytes[i-2] != asn1PrintableStringTag {
		return pkix.Extension{}, fmt.Errorf("Unexpected asn1 encoding: i=%d asn1=% x", i, asn1Bytes)
	}
	asn1Bytes[i-2] = asn1VisibleStringTag
	ext := pkix.Extension{
		Id:       idCertificatePolicies,
		Critical: false,
		Value:    asn1Bytes,
	}
	return ext, nil
}
Example #30
0
// Sign computes an ECDSA sigature over the contextualized data, using the
// private key of the signer.
func (s *Signer) Sign(data []byte, context string) ([]byte, error) {
	ch, err := s.CreateHeader()
	if err != nil {
		return nil, err
	}

	// TODO(tmroeder): for compatibility with the C++ version, we should
	// compute ECDSA signatures over hashes truncated to fit in the ECDSA
	// signature.
	b, err := contextualizedSHA256(ch, data, context, sha256.Size)
	if err != nil {
		return nil, err
	}

	R, S, err := ecdsa.Sign(rand.Reader, s.ec, b)
	if err != nil {
		return nil, err
	}

	m, err := asn1.Marshal(ecdsaSignature{R, S})
	if err != nil {
		return nil, err
	}

	sd := &SignedData{
		Header:    ch,
		Signature: m,
	}

	return proto.Marshal(sd)
}