text
stringlengths
2
1.1M
id
stringlengths
11
117
metadata
dict
__index_level_0__
int64
0
885
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package acmetest provides types for testing acme and autocert packages. // // TODO: Consider moving this to x/crypto/acme/internal/acmetest for acme tests as well. package acmetest import ( "context" "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/base64" "encoding/json" "encoding/pem" "fmt" "io" "math/big" "net" "net/http" "net/http/httptest" "path" "strconv" "strings" "sync" "testing" "time" "golang.org/x/crypto/acme" ) // CAServer is a simple test server which implements ACME spec bits needed for testing. type CAServer struct { rootKey crypto.Signer rootCert []byte // DER encoding rootTemplate *x509.Certificate t *testing.T server *httptest.Server issuer pkix.Name challengeTypes []string url string roots *x509.CertPool eabRequired bool mu sync.Mutex certCount int // number of issued certs acctRegistered bool // set once an account has been registered domainAddr map[string]string // domain name to addr:port resolution domainGetCert map[string]getCertificateFunc // domain name to GetCertificate function domainHandler map[string]http.Handler // domain name to Handle function validAuthz map[string]*authorization // valid authz, keyed by domain name authorizations []*authorization // all authz, index is used as ID orders []*order // index is used as order ID errors []error // encountered client errors } type getCertificateFunc func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) // NewCAServer creates a new ACME test server. The returned CAServer issues // certs signed with the CA roots available in the Roots field. func NewCAServer(t *testing.T) *CAServer { ca := &CAServer{t: t, challengeTypes: []string{"fake-01", "tls-alpn-01", "http-01"}, domainAddr: make(map[string]string), domainGetCert: make(map[string]getCertificateFunc), domainHandler: make(map[string]http.Handler), validAuthz: make(map[string]*authorization), } ca.server = httptest.NewUnstartedServer(http.HandlerFunc(ca.handle)) r, err := rand.Int(rand.Reader, big.NewInt(1000000)) if err != nil { panic(fmt.Sprintf("rand.Int: %v", err)) } ca.issuer = pkix.Name{ Organization: []string{"Test Acme Co"}, CommonName: "Root CA " + r.String(), } return ca } func (ca *CAServer) generateRoot() { key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { panic(fmt.Sprintf("ecdsa.GenerateKey: %v", err)) } tmpl := &x509.Certificate{ SerialNumber: big.NewInt(1), Subject: ca.issuer, NotBefore: time.Now(), NotAfter: time.Now().Add(365 * 24 * time.Hour), KeyUsage: x509.KeyUsageCertSign, BasicConstraintsValid: true, IsCA: true, } der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) if err != nil { panic(fmt.Sprintf("x509.CreateCertificate: %v", err)) } cert, err := x509.ParseCertificate(der) if err != nil { panic(fmt.Sprintf("x509.ParseCertificate: %v", err)) } ca.roots = x509.NewCertPool() ca.roots.AddCert(cert) ca.rootKey = key ca.rootCert = der ca.rootTemplate = tmpl } // IssuerName sets the name of the issuing CA. func (ca *CAServer) IssuerName(name pkix.Name) *CAServer { if ca.url != "" { panic("IssuerName must be called before Start") } ca.issuer = name return ca } // ChallengeTypes sets the supported challenge types. func (ca *CAServer) ChallengeTypes(types ...string) *CAServer { if ca.url != "" { panic("ChallengeTypes must be called before Start") } ca.challengeTypes = types return ca } // URL returns the server address, after Start has been called. func (ca *CAServer) URL() string { if ca.url == "" { panic("URL called before Start") } return ca.url } // Roots returns a pool cointaining the CA root. func (ca *CAServer) Roots() *x509.CertPool { if ca.url == "" { panic("Roots called before Start") } return ca.roots } // ExternalAccountRequired makes an EAB JWS required for account registration. func (ca *CAServer) ExternalAccountRequired() *CAServer { if ca.url != "" { panic("ExternalAccountRequired must be called before Start") } ca.eabRequired = true return ca } // Start starts serving requests. The server address becomes available in the // URL field. func (ca *CAServer) Start() *CAServer { if ca.url == "" { ca.generateRoot() ca.server.Start() ca.t.Cleanup(ca.server.Close) ca.url = ca.server.URL } return ca } func (ca *CAServer) serverURL(format string, arg ...interface{}) string { return ca.server.URL + fmt.Sprintf(format, arg...) } func (ca *CAServer) addr(domain string) (string, bool) { ca.mu.Lock() defer ca.mu.Unlock() addr, ok := ca.domainAddr[domain] return addr, ok } func (ca *CAServer) getCert(domain string) (getCertificateFunc, bool) { ca.mu.Lock() defer ca.mu.Unlock() f, ok := ca.domainGetCert[domain] return f, ok } func (ca *CAServer) getHandler(domain string) (http.Handler, bool) { ca.mu.Lock() defer ca.mu.Unlock() h, ok := ca.domainHandler[domain] return h, ok } func (ca *CAServer) httpErrorf(w http.ResponseWriter, code int, format string, a ...interface{}) { s := fmt.Sprintf(format, a...) ca.t.Errorf(format, a...) http.Error(w, s, code) } // Resolve adds a domain to address resolution for the ca to dial to // when validating challenges for the domain authorization. func (ca *CAServer) Resolve(domain, addr string) { ca.mu.Lock() defer ca.mu.Unlock() ca.domainAddr[domain] = addr } // ResolveGetCertificate redirects TLS connections for domain to f when // validating challenges for the domain authorization. func (ca *CAServer) ResolveGetCertificate(domain string, f getCertificateFunc) { ca.mu.Lock() defer ca.mu.Unlock() ca.domainGetCert[domain] = f } // ResolveHandler redirects HTTP requests for domain to f when // validating challenges for the domain authorization. func (ca *CAServer) ResolveHandler(domain string, h http.Handler) { ca.mu.Lock() defer ca.mu.Unlock() ca.domainHandler[domain] = h } type discovery struct { NewNonce string `json:"newNonce"` NewAccount string `json:"newAccount"` NewOrder string `json:"newOrder"` NewAuthz string `json:"newAuthz"` Meta discoveryMeta `json:"meta,omitempty"` } type discoveryMeta struct { ExternalAccountRequired bool `json:"externalAccountRequired,omitempty"` } type challenge struct { URI string `json:"uri"` Type string `json:"type"` Token string `json:"token"` } type authorization struct { Status string `json:"status"` Challenges []challenge `json:"challenges"` domain string id int } type order struct { Status string `json:"status"` AuthzURLs []string `json:"authorizations"` FinalizeURL string `json:"finalize"` // CSR submit URL CertURL string `json:"certificate"` // already issued cert leaf []byte // issued cert in DER format } func (ca *CAServer) handle(w http.ResponseWriter, r *http.Request) { ca.t.Logf("%s %s", r.Method, r.URL) w.Header().Set("Replay-Nonce", "nonce") // TODO: Verify nonce header for all POST requests. switch { default: ca.httpErrorf(w, http.StatusBadRequest, "unrecognized r.URL.Path: %s", r.URL.Path) // Discovery request. case r.URL.Path == "/": resp := &discovery{ NewNonce: ca.serverURL("/new-nonce"), NewAccount: ca.serverURL("/new-account"), NewOrder: ca.serverURL("/new-order"), Meta: discoveryMeta{ ExternalAccountRequired: ca.eabRequired, }, } if err := json.NewEncoder(w).Encode(resp); err != nil { panic(fmt.Sprintf("discovery response: %v", err)) } // Nonce requests. case r.URL.Path == "/new-nonce": // Nonce values are always set. Nothing else to do. return // Client key registration request. case r.URL.Path == "/new-account": ca.mu.Lock() defer ca.mu.Unlock() if ca.acctRegistered { ca.httpErrorf(w, http.StatusServiceUnavailable, "multiple accounts are not implemented") return } ca.acctRegistered = true var req struct { ExternalAccountBinding json.RawMessage } if err := decodePayload(&req, r.Body); err != nil { ca.httpErrorf(w, http.StatusBadRequest, err.Error()) return } if ca.eabRequired && len(req.ExternalAccountBinding) == 0 { ca.httpErrorf(w, http.StatusBadRequest, "registration failed: no JWS for EAB") return } // TODO: Check the user account key against a ca.accountKeys? w.Header().Set("Location", ca.serverURL("/accounts/1")) w.WriteHeader(http.StatusCreated) w.Write([]byte("{}")) // New order request. case r.URL.Path == "/new-order": var req struct { Identifiers []struct{ Value string } } if err := decodePayload(&req, r.Body); err != nil { ca.httpErrorf(w, http.StatusBadRequest, err.Error()) return } ca.mu.Lock() defer ca.mu.Unlock() o := &order{Status: acme.StatusPending} for _, id := range req.Identifiers { z := ca.authz(id.Value) o.AuthzURLs = append(o.AuthzURLs, ca.serverURL("/authz/%d", z.id)) } orderID := len(ca.orders) ca.orders = append(ca.orders, o) w.Header().Set("Location", ca.serverURL("/orders/%d", orderID)) w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(o); err != nil { panic(err) } // Existing order status requests. case strings.HasPrefix(r.URL.Path, "/orders/"): ca.mu.Lock() defer ca.mu.Unlock() o, err := ca.storedOrder(strings.TrimPrefix(r.URL.Path, "/orders/")) if err != nil { ca.httpErrorf(w, http.StatusBadRequest, err.Error()) return } if err := json.NewEncoder(w).Encode(o); err != nil { panic(err) } // Accept challenge requests. case strings.HasPrefix(r.URL.Path, "/challenge/"): parts := strings.Split(r.URL.Path, "/") typ, id := parts[len(parts)-2], parts[len(parts)-1] ca.mu.Lock() supported := false for _, suppTyp := range ca.challengeTypes { if suppTyp == typ { supported = true } } a, err := ca.storedAuthz(id) ca.mu.Unlock() if !supported { ca.httpErrorf(w, http.StatusBadRequest, "unsupported challenge: %v", typ) return } if err != nil { ca.httpErrorf(w, http.StatusBadRequest, "challenge accept: %v", err) return } ca.validateChallenge(a, typ) w.Write([]byte("{}")) // Get authorization status requests. case strings.HasPrefix(r.URL.Path, "/authz/"): var req struct{ Status string } decodePayload(&req, r.Body) deactivate := req.Status == "deactivated" ca.mu.Lock() defer ca.mu.Unlock() authz, err := ca.storedAuthz(strings.TrimPrefix(r.URL.Path, "/authz/")) if err != nil { ca.httpErrorf(w, http.StatusNotFound, "%v", err) return } if deactivate { // Note we don't invalidate authorized orders as we should. authz.Status = "deactivated" ca.t.Logf("authz %d is now %s", authz.id, authz.Status) ca.updatePendingOrders() } if err := json.NewEncoder(w).Encode(authz); err != nil { panic(fmt.Sprintf("encoding authz %d: %v", authz.id, err)) } // Certificate issuance request. case strings.HasPrefix(r.URL.Path, "/new-cert/"): ca.mu.Lock() defer ca.mu.Unlock() orderID := strings.TrimPrefix(r.URL.Path, "/new-cert/") o, err := ca.storedOrder(orderID) if err != nil { ca.httpErrorf(w, http.StatusBadRequest, err.Error()) return } if o.Status != acme.StatusReady { ca.httpErrorf(w, http.StatusForbidden, "order status: %s", o.Status) return } // Validate CSR request. var req struct { CSR string `json:"csr"` } decodePayload(&req, r.Body) b, _ := base64.RawURLEncoding.DecodeString(req.CSR) csr, err := x509.ParseCertificateRequest(b) if err != nil { ca.httpErrorf(w, http.StatusBadRequest, err.Error()) return } // Issue the certificate. der, err := ca.leafCert(csr) if err != nil { ca.httpErrorf(w, http.StatusBadRequest, "new-cert response: ca.leafCert: %v", err) return } o.leaf = der o.CertURL = ca.serverURL("/issued-cert/%s", orderID) o.Status = acme.StatusValid if err := json.NewEncoder(w).Encode(o); err != nil { panic(err) } // Already issued cert download requests. case strings.HasPrefix(r.URL.Path, "/issued-cert/"): ca.mu.Lock() defer ca.mu.Unlock() o, err := ca.storedOrder(strings.TrimPrefix(r.URL.Path, "/issued-cert/")) if err != nil { ca.httpErrorf(w, http.StatusBadRequest, err.Error()) return } if o.Status != acme.StatusValid { ca.httpErrorf(w, http.StatusForbidden, "order status: %s", o.Status) return } w.Header().Set("Content-Type", "application/pem-certificate-chain") pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: o.leaf}) pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: ca.rootCert}) } } // storedOrder retrieves a previously created order at index i. // It requires ca.mu to be locked. func (ca *CAServer) storedOrder(i string) (*order, error) { idx, err := strconv.Atoi(i) if err != nil { return nil, fmt.Errorf("storedOrder: %v", err) } if idx < 0 { return nil, fmt.Errorf("storedOrder: invalid order index %d", idx) } if idx > len(ca.orders)-1 { return nil, fmt.Errorf("storedOrder: no such order %d", idx) } ca.updatePendingOrders() return ca.orders[idx], nil } // storedAuthz retrieves a previously created authz at index i. // It requires ca.mu to be locked. func (ca *CAServer) storedAuthz(i string) (*authorization, error) { idx, err := strconv.Atoi(i) if err != nil { return nil, fmt.Errorf("storedAuthz: %v", err) } if idx < 0 { return nil, fmt.Errorf("storedAuthz: invalid authz index %d", idx) } if idx > len(ca.authorizations)-1 { return nil, fmt.Errorf("storedAuthz: no such authz %d", idx) } return ca.authorizations[idx], nil } // authz returns an existing valid authorization for the identifier or creates a // new one. It requires ca.mu to be locked. func (ca *CAServer) authz(identifier string) *authorization { authz, ok := ca.validAuthz[identifier] if !ok { authzId := len(ca.authorizations) authz = &authorization{ id: authzId, domain: identifier, Status: acme.StatusPending, } for _, typ := range ca.challengeTypes { authz.Challenges = append(authz.Challenges, challenge{ Type: typ, URI: ca.serverURL("/challenge/%s/%d", typ, authzId), Token: challengeToken(authz.domain, typ, authzId), }) } ca.authorizations = append(ca.authorizations, authz) } return authz } // leafCert issues a new certificate. // It requires ca.mu to be locked. func (ca *CAServer) leafCert(csr *x509.CertificateRequest) (der []byte, err error) { ca.certCount++ // next leaf cert serial number leaf := &x509.Certificate{ SerialNumber: big.NewInt(int64(ca.certCount)), Subject: pkix.Name{Organization: []string{"Test Acme Co"}}, NotBefore: time.Now(), NotAfter: time.Now().Add(90 * 24 * time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, DNSNames: csr.DNSNames, BasicConstraintsValid: true, } if len(csr.DNSNames) == 0 { leaf.DNSNames = []string{csr.Subject.CommonName} } return x509.CreateCertificate(rand.Reader, leaf, ca.rootTemplate, csr.PublicKey, ca.rootKey) } // LeafCert issues a leaf certificate. func (ca *CAServer) LeafCert(name, keyType string, notBefore, notAfter time.Time) *tls.Certificate { if ca.url == "" { panic("LeafCert called before Start") } ca.mu.Lock() defer ca.mu.Unlock() var pk crypto.Signer switch keyType { case "RSA": var err error pk, err = rsa.GenerateKey(rand.Reader, 1024) if err != nil { ca.t.Fatal(err) } case "ECDSA": var err error pk, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { ca.t.Fatal(err) } default: panic("LeafCert: unknown key type") } ca.certCount++ // next leaf cert serial number leaf := &x509.Certificate{ SerialNumber: big.NewInt(int64(ca.certCount)), Subject: pkix.Name{Organization: []string{"Test Acme Co"}}, NotBefore: notBefore, NotAfter: notAfter, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, DNSNames: []string{name}, BasicConstraintsValid: true, } der, err := x509.CreateCertificate(rand.Reader, leaf, ca.rootTemplate, pk.Public(), ca.rootKey) if err != nil { ca.t.Fatal(err) } return &tls.Certificate{ Certificate: [][]byte{der}, PrivateKey: pk, } } func (ca *CAServer) validateChallenge(authz *authorization, typ string) { var err error switch typ { case "tls-alpn-01": err = ca.verifyALPNChallenge(authz) case "http-01": err = ca.verifyHTTPChallenge(authz) default: panic(fmt.Sprintf("validation of %q is not implemented", typ)) } ca.mu.Lock() defer ca.mu.Unlock() if err != nil { authz.Status = "invalid" } else { authz.Status = "valid" ca.validAuthz[authz.domain] = authz } ca.t.Logf("validated %q for %q, err: %v", typ, authz.domain, err) ca.t.Logf("authz %d is now %s", authz.id, authz.Status) ca.updatePendingOrders() } func (ca *CAServer) updatePendingOrders() { // Update all pending orders. // An order becomes "ready" if all authorizations are "valid". // An order becomes "invalid" if any authorization is "invalid". // Status changes: https://tools.ietf.org/html/rfc8555#section-7.1.6 for i, o := range ca.orders { if o.Status != acme.StatusPending { continue } countValid, countInvalid := ca.validateAuthzURLs(o.AuthzURLs, i) if countInvalid > 0 { o.Status = acme.StatusInvalid ca.t.Logf("order %d is now invalid", i) continue } if countValid == len(o.AuthzURLs) { o.Status = acme.StatusReady o.FinalizeURL = ca.serverURL("/new-cert/%d", i) ca.t.Logf("order %d is now ready", i) } } } func (ca *CAServer) validateAuthzURLs(urls []string, orderNum int) (countValid, countInvalid int) { for _, zurl := range urls { z, err := ca.storedAuthz(path.Base(zurl)) if err != nil { ca.t.Logf("no authz %q for order %d", zurl, orderNum) continue } if z.Status == acme.StatusInvalid { countInvalid++ } if z.Status == acme.StatusValid { countValid++ } } return countValid, countInvalid } func (ca *CAServer) verifyALPNChallenge(a *authorization) error { const acmeALPNProto = "acme-tls/1" addr, haveAddr := ca.addr(a.domain) getCert, haveGetCert := ca.getCert(a.domain) if !haveAddr && !haveGetCert { return fmt.Errorf("no resolution information for %q", a.domain) } if haveAddr && haveGetCert { return fmt.Errorf("overlapping resolution information for %q", a.domain) } var crt *x509.Certificate switch { case haveAddr: conn, err := tls.Dial("tcp", addr, &tls.Config{ ServerName: a.domain, InsecureSkipVerify: true, NextProtos: []string{acmeALPNProto}, MinVersion: tls.VersionTLS12, }) if err != nil { return err } if v := conn.ConnectionState().NegotiatedProtocol; v != acmeALPNProto { return fmt.Errorf("CAServer: verifyALPNChallenge: negotiated proto is %q; want %q", v, acmeALPNProto) } if n := len(conn.ConnectionState().PeerCertificates); n != 1 { return fmt.Errorf("len(PeerCertificates) = %d; want 1", n) } crt = conn.ConnectionState().PeerCertificates[0] case haveGetCert: hello := &tls.ClientHelloInfo{ ServerName: a.domain, // TODO: support selecting ECDSA. CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305}, SupportedProtos: []string{acme.ALPNProto}, SupportedVersions: []uint16{tls.VersionTLS12}, } c, err := getCert(hello) if err != nil { return err } crt, err = x509.ParseCertificate(c.Certificate[0]) if err != nil { return err } } if err := crt.VerifyHostname(a.domain); err != nil { return fmt.Errorf("verifyALPNChallenge: VerifyHostname: %v", err) } // See RFC 8737, Section 6.1. oid := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31} for _, x := range crt.Extensions { if x.Id.Equal(oid) { // TODO: check the token. return nil } } return fmt.Errorf("verifyTokenCert: no id-pe-acmeIdentifier extension found") } func (ca *CAServer) verifyHTTPChallenge(a *authorization) error { addr, haveAddr := ca.addr(a.domain) handler, haveHandler := ca.getHandler(a.domain) if !haveAddr && !haveHandler { return fmt.Errorf("no resolution information for %q", a.domain) } if haveAddr && haveHandler { return fmt.Errorf("overlapping resolution information for %q", a.domain) } token := challengeToken(a.domain, "http-01", a.id) path := "/.well-known/acme-challenge/" + token var body string switch { case haveAddr: t := &http.Transport{ DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { return (&net.Dialer{}).DialContext(ctx, network, addr) }, } req, err := http.NewRequest("GET", "http://"+a.domain+path, nil) if err != nil { return err } res, err := t.RoundTrip(req) if err != nil { return err } if res.StatusCode != http.StatusOK { return fmt.Errorf("http token: w.Code = %d; want %d", res.StatusCode, http.StatusOK) } b, err := io.ReadAll(res.Body) if err != nil { return err } body = string(b) case haveHandler: r := httptest.NewRequest("GET", path, nil) r.Host = a.domain w := httptest.NewRecorder() handler.ServeHTTP(w, r) if w.Code != http.StatusOK { return fmt.Errorf("http token: w.Code = %d; want %d", w.Code, http.StatusOK) } body = w.Body.String() } if !strings.HasPrefix(body, token) { return fmt.Errorf("http token value = %q; want 'token-http-01.' prefix", body) } return nil } func decodePayload(v interface{}, r io.Reader) error { var req struct{ Payload string } if err := json.NewDecoder(r).Decode(&req); err != nil { return err } payload, err := base64.RawURLEncoding.DecodeString(req.Payload) if err != nil { return err } return json.Unmarshal(payload, v) } func challengeToken(domain, challType string, authzID int) string { return fmt.Sprintf("token-%s-%s-%d", domain, challType, authzID) } func unique(a []string) []string { seen := make(map[string]bool) var res []string for _, s := range a { if s != "" && !seen[s] { seen[s] = true res = append(res, s) } } return res }
crypto/acme/autocert/internal/acmetest/ca.go/0
{ "file_path": "crypto/acme/autocert/internal/acmetest/ca.go", "repo_id": "crypto", "token_count": 9238 }
0
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build amd64 && gc && !purego package argon2 import "golang.org/x/sys/cpu" func init() { useSSE4 = cpu.X86.HasSSE41 } //go:noescape func mixBlocksSSE2(out, a, b, c *block) //go:noescape func xorBlocksSSE2(out, a, b, c *block) //go:noescape func blamkaSSE4(b *block) func processBlockSSE(out, in1, in2 *block, xor bool) { var t block mixBlocksSSE2(&t, in1, in2, &t) if useSSE4 { blamkaSSE4(&t) } else { for i := 0; i < blockLength; i += 16 { blamkaGeneric( &t[i+0], &t[i+1], &t[i+2], &t[i+3], &t[i+4], &t[i+5], &t[i+6], &t[i+7], &t[i+8], &t[i+9], &t[i+10], &t[i+11], &t[i+12], &t[i+13], &t[i+14], &t[i+15], ) } for i := 0; i < blockLength/8; i += 2 { blamkaGeneric( &t[i], &t[i+1], &t[16+i], &t[16+i+1], &t[32+i], &t[32+i+1], &t[48+i], &t[48+i+1], &t[64+i], &t[64+i+1], &t[80+i], &t[80+i+1], &t[96+i], &t[96+i+1], &t[112+i], &t[112+i+1], ) } } if xor { xorBlocksSSE2(out, in1, in2, &t) } else { mixBlocksSSE2(out, in1, in2, &t) } } func processBlock(out, in1, in2 *block) { processBlockSSE(out, in1, in2, false) } func processBlockXOR(out, in1, in2 *block) { processBlockSSE(out, in1, in2, true) }
crypto/argon2/blamka_amd64.go/0
{ "file_path": "crypto/argon2/blamka_amd64.go", "repo_id": "crypto", "token_count": 729 }
1
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package blake2s implements the BLAKE2s hash algorithm defined by RFC 7693 // and the extendable output function (XOF) BLAKE2Xs. // // BLAKE2s is optimized for 8- to 32-bit platforms and produces digests of any // size between 1 and 32 bytes. // For a detailed specification of BLAKE2s see https://blake2.net/blake2.pdf // and for BLAKE2Xs see https://blake2.net/blake2x.pdf // // If you aren't sure which function you need, use BLAKE2s (Sum256 or New256). // If you need a secret-key MAC (message authentication code), use the New256 // function with a non-nil key. // // BLAKE2X is a construction to compute hash values larger than 32 bytes. It // can produce hash values between 0 and 65535 bytes. package blake2s import ( "crypto" "encoding/binary" "errors" "hash" ) const ( // The blocksize of BLAKE2s in bytes. BlockSize = 64 // The hash size of BLAKE2s-256 in bytes. Size = 32 // The hash size of BLAKE2s-128 in bytes. Size128 = 16 ) var errKeySize = errors.New("blake2s: invalid key size") var iv = [8]uint32{ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, } // Sum256 returns the BLAKE2s-256 checksum of the data. func Sum256(data []byte) [Size]byte { var sum [Size]byte checkSum(&sum, Size, data) return sum } // New256 returns a new hash.Hash computing the BLAKE2s-256 checksum. A non-nil // key turns the hash into a MAC. The key must between zero and 32 bytes long. // When the key is nil, the returned hash.Hash implements BinaryMarshaler // and BinaryUnmarshaler for state (de)serialization as documented by hash.Hash. func New256(key []byte) (hash.Hash, error) { return newDigest(Size, key) } func init() { crypto.RegisterHash(crypto.BLAKE2s_256, func() hash.Hash { h, _ := New256(nil) return h }) } // New128 returns a new hash.Hash computing the BLAKE2s-128 checksum given a // non-empty key. Note that a 128-bit digest is too small to be secure as a // cryptographic hash and should only be used as a MAC, thus the key argument // is not optional. func New128(key []byte) (hash.Hash, error) { if len(key) == 0 { return nil, errors.New("blake2s: a key is required for a 128-bit hash") } return newDigest(Size128, key) } func newDigest(hashSize int, key []byte) (*digest, error) { if len(key) > Size { return nil, errKeySize } d := &digest{ size: hashSize, keyLen: len(key), } copy(d.key[:], key) d.Reset() return d, nil } func checkSum(sum *[Size]byte, hashSize int, data []byte) { var ( h [8]uint32 c [2]uint32 ) h = iv h[0] ^= uint32(hashSize) | (1 << 16) | (1 << 24) if length := len(data); length > BlockSize { n := length &^ (BlockSize - 1) if length == n { n -= BlockSize } hashBlocks(&h, &c, 0, data[:n]) data = data[n:] } var block [BlockSize]byte offset := copy(block[:], data) remaining := uint32(BlockSize - offset) if c[0] < remaining { c[1]-- } c[0] -= remaining hashBlocks(&h, &c, 0xFFFFFFFF, block[:]) for i, v := range h { binary.LittleEndian.PutUint32(sum[4*i:], v) } } type digest struct { h [8]uint32 c [2]uint32 size int block [BlockSize]byte offset int key [BlockSize]byte keyLen int } const ( magic = "b2s" marshaledSize = len(magic) + 8*4 + 2*4 + 1 + BlockSize + 1 ) func (d *digest) MarshalBinary() ([]byte, error) { if d.keyLen != 0 { return nil, errors.New("crypto/blake2s: cannot marshal MACs") } b := make([]byte, 0, marshaledSize) b = append(b, magic...) for i := 0; i < 8; i++ { b = appendUint32(b, d.h[i]) } b = appendUint32(b, d.c[0]) b = appendUint32(b, d.c[1]) // Maximum value for size is 32 b = append(b, byte(d.size)) b = append(b, d.block[:]...) b = append(b, byte(d.offset)) return b, nil } func (d *digest) UnmarshalBinary(b []byte) error { if len(b) < len(magic) || string(b[:len(magic)]) != magic { return errors.New("crypto/blake2s: invalid hash state identifier") } if len(b) != marshaledSize { return errors.New("crypto/blake2s: invalid hash state size") } b = b[len(magic):] for i := 0; i < 8; i++ { b, d.h[i] = consumeUint32(b) } b, d.c[0] = consumeUint32(b) b, d.c[1] = consumeUint32(b) d.size = int(b[0]) b = b[1:] copy(d.block[:], b[:BlockSize]) b = b[BlockSize:] d.offset = int(b[0]) return nil } func (d *digest) BlockSize() int { return BlockSize } func (d *digest) Size() int { return d.size } func (d *digest) Reset() { d.h = iv d.h[0] ^= uint32(d.size) | (uint32(d.keyLen) << 8) | (1 << 16) | (1 << 24) d.offset, d.c[0], d.c[1] = 0, 0, 0 if d.keyLen > 0 { d.block = d.key d.offset = BlockSize } } func (d *digest) Write(p []byte) (n int, err error) { n = len(p) if d.offset > 0 { remaining := BlockSize - d.offset if n <= remaining { d.offset += copy(d.block[d.offset:], p) return } copy(d.block[d.offset:], p[:remaining]) hashBlocks(&d.h, &d.c, 0, d.block[:]) d.offset = 0 p = p[remaining:] } if length := len(p); length > BlockSize { nn := length &^ (BlockSize - 1) if length == nn { nn -= BlockSize } hashBlocks(&d.h, &d.c, 0, p[:nn]) p = p[nn:] } d.offset += copy(d.block[:], p) return } func (d *digest) Sum(sum []byte) []byte { var hash [Size]byte d.finalize(&hash) return append(sum, hash[:d.size]...) } func (d *digest) finalize(hash *[Size]byte) { var block [BlockSize]byte h := d.h c := d.c copy(block[:], d.block[:d.offset]) remaining := uint32(BlockSize - d.offset) if c[0] < remaining { c[1]-- } c[0] -= remaining hashBlocks(&h, &c, 0xFFFFFFFF, block[:]) for i, v := range h { binary.LittleEndian.PutUint32(hash[4*i:], v) } } func appendUint32(b []byte, x uint32) []byte { var a [4]byte binary.BigEndian.PutUint32(a[:], x) return append(b, a[:]...) } func consumeUint32(b []byte) ([]byte, uint32) { x := binary.BigEndian.Uint32(b) return b[4:], x }
crypto/blake2s/blake2s.go/0
{ "file_path": "crypto/blake2s/blake2s.go", "repo_id": "crypto", "token_count": 2521 }
2
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bn256 import ( "math/big" ) // curvePoint implements the elliptic curve y²=x³+3. Points are kept in // Jacobian form and t=z² when valid. G₁ is the set of points of this curve on // GF(p). type curvePoint struct { x, y, z, t *big.Int } var curveB = new(big.Int).SetInt64(3) // curveGen is the generator of G₁. var curveGen = &curvePoint{ new(big.Int).SetInt64(1), new(big.Int).SetInt64(-2), new(big.Int).SetInt64(1), new(big.Int).SetInt64(1), } func newCurvePoint(pool *bnPool) *curvePoint { return &curvePoint{ pool.Get(), pool.Get(), pool.Get(), pool.Get(), } } func (c *curvePoint) String() string { c.MakeAffine(new(bnPool)) return "(" + c.x.String() + ", " + c.y.String() + ")" } func (c *curvePoint) Put(pool *bnPool) { pool.Put(c.x) pool.Put(c.y) pool.Put(c.z) pool.Put(c.t) } func (c *curvePoint) Set(a *curvePoint) { c.x.Set(a.x) c.y.Set(a.y) c.z.Set(a.z) c.t.Set(a.t) } // IsOnCurve returns true iff c is on the curve where c must be in affine form. func (c *curvePoint) IsOnCurve() bool { yy := new(big.Int).Mul(c.y, c.y) xxx := new(big.Int).Mul(c.x, c.x) xxx.Mul(xxx, c.x) yy.Sub(yy, xxx) yy.Sub(yy, curveB) if yy.Sign() < 0 || yy.Cmp(p) >= 0 { yy.Mod(yy, p) } return yy.Sign() == 0 } func (c *curvePoint) SetInfinity() { c.z.SetInt64(0) } func (c *curvePoint) IsInfinity() bool { return c.z.Sign() == 0 } func (c *curvePoint) Add(a, b *curvePoint, pool *bnPool) { if a.IsInfinity() { c.Set(b) return } if b.IsInfinity() { c.Set(a) return } // See http://hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2007-bl.op3 // Normalize the points by replacing a = [x1:y1:z1] and b = [x2:y2:z2] // by [u1:s1:z1·z2] and [u2:s2:z1·z2] // where u1 = x1·z2², s1 = y1·z2³ and u1 = x2·z1², s2 = y2·z1³ z1z1 := pool.Get().Mul(a.z, a.z) z1z1.Mod(z1z1, p) z2z2 := pool.Get().Mul(b.z, b.z) z2z2.Mod(z2z2, p) u1 := pool.Get().Mul(a.x, z2z2) u1.Mod(u1, p) u2 := pool.Get().Mul(b.x, z1z1) u2.Mod(u2, p) t := pool.Get().Mul(b.z, z2z2) t.Mod(t, p) s1 := pool.Get().Mul(a.y, t) s1.Mod(s1, p) t.Mul(a.z, z1z1) t.Mod(t, p) s2 := pool.Get().Mul(b.y, t) s2.Mod(s2, p) // Compute x = (2h)²(s²-u1-u2) // where s = (s2-s1)/(u2-u1) is the slope of the line through // (u1,s1) and (u2,s2). The extra factor 2h = 2(u2-u1) comes from the value of z below. // This is also: // 4(s2-s1)² - 4h²(u1+u2) = 4(s2-s1)² - 4h³ - 4h²(2u1) // = r² - j - 2v // with the notations below. h := pool.Get().Sub(u2, u1) xEqual := h.Sign() == 0 t.Add(h, h) // i = 4h² i := pool.Get().Mul(t, t) i.Mod(i, p) // j = 4h³ j := pool.Get().Mul(h, i) j.Mod(j, p) t.Sub(s2, s1) yEqual := t.Sign() == 0 if xEqual && yEqual { c.Double(a, pool) return } r := pool.Get().Add(t, t) v := pool.Get().Mul(u1, i) v.Mod(v, p) // t4 = 4(s2-s1)² t4 := pool.Get().Mul(r, r) t4.Mod(t4, p) t.Add(v, v) t6 := pool.Get().Sub(t4, j) c.x.Sub(t6, t) // Set y = -(2h)³(s1 + s*(x/4h²-u1)) // This is also // y = - 2·s1·j - (s2-s1)(2x - 2i·u1) = r(v-x) - 2·s1·j t.Sub(v, c.x) // t7 t4.Mul(s1, j) // t8 t4.Mod(t4, p) t6.Add(t4, t4) // t9 t4.Mul(r, t) // t10 t4.Mod(t4, p) c.y.Sub(t4, t6) // Set z = 2(u2-u1)·z1·z2 = 2h·z1·z2 t.Add(a.z, b.z) // t11 t4.Mul(t, t) // t12 t4.Mod(t4, p) t.Sub(t4, z1z1) // t13 t4.Sub(t, z2z2) // t14 c.z.Mul(t4, h) c.z.Mod(c.z, p) pool.Put(z1z1) pool.Put(z2z2) pool.Put(u1) pool.Put(u2) pool.Put(t) pool.Put(s1) pool.Put(s2) pool.Put(h) pool.Put(i) pool.Put(j) pool.Put(r) pool.Put(v) pool.Put(t4) pool.Put(t6) } func (c *curvePoint) Double(a *curvePoint, pool *bnPool) { // See http://hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/doubling/dbl-2009-l.op3 A := pool.Get().Mul(a.x, a.x) A.Mod(A, p) B := pool.Get().Mul(a.y, a.y) B.Mod(B, p) C := pool.Get().Mul(B, B) C.Mod(C, p) t := pool.Get().Add(a.x, B) t2 := pool.Get().Mul(t, t) t2.Mod(t2, p) t.Sub(t2, A) t2.Sub(t, C) d := pool.Get().Add(t2, t2) t.Add(A, A) e := pool.Get().Add(t, A) f := pool.Get().Mul(e, e) f.Mod(f, p) t.Add(d, d) c.x.Sub(f, t) t.Add(C, C) t2.Add(t, t) t.Add(t2, t2) c.y.Sub(d, c.x) t2.Mul(e, c.y) t2.Mod(t2, p) c.y.Sub(t2, t) t.Mul(a.y, a.z) t.Mod(t, p) c.z.Add(t, t) pool.Put(A) pool.Put(B) pool.Put(C) pool.Put(t) pool.Put(t2) pool.Put(d) pool.Put(e) pool.Put(f) } func (c *curvePoint) Mul(a *curvePoint, scalar *big.Int, pool *bnPool) *curvePoint { sum := newCurvePoint(pool) sum.SetInfinity() t := newCurvePoint(pool) for i := scalar.BitLen(); i >= 0; i-- { t.Double(sum, pool) if scalar.Bit(i) != 0 { sum.Add(t, a, pool) } else { sum.Set(t) } } c.Set(sum) sum.Put(pool) t.Put(pool) return c } // MakeAffine converts c to affine form and returns c. If c is ∞, then it sets // c to 0 : 1 : 0. func (c *curvePoint) MakeAffine(pool *bnPool) *curvePoint { if words := c.z.Bits(); len(words) == 1 && words[0] == 1 { return c } if c.IsInfinity() { c.x.SetInt64(0) c.y.SetInt64(1) c.z.SetInt64(0) c.t.SetInt64(0) return c } zInv := pool.Get().ModInverse(c.z, p) t := pool.Get().Mul(c.y, zInv) t.Mod(t, p) zInv2 := pool.Get().Mul(zInv, zInv) zInv2.Mod(zInv2, p) c.y.Mul(t, zInv2) c.y.Mod(c.y, p) t.Mul(c.x, zInv2) t.Mod(t, p) c.x.Set(t) c.z.SetInt64(1) c.t.SetInt64(1) pool.Put(zInv) pool.Put(t) pool.Put(zInv2) return c } func (c *curvePoint) Negative(a *curvePoint) { c.x.Set(a.x) c.y.Neg(a.y) c.z.Set(a.z) c.t.SetInt64(0) }
crypto/bn256/curve.go/0
{ "file_path": "crypto/bn256/curve.go", "repo_id": "crypto", "token_count": 3206 }
3
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build gc && !purego #include "go_asm.h" #include "textflag.h" // This is an implementation of the ChaCha20 encryption algorithm as // specified in RFC 7539. It uses vector instructions to compute // 4 keystream blocks in parallel (256 bytes) which are then XORed // with the bytes in the input slice. GLOBL ·constants<>(SB), RODATA|NOPTR, $32 // BSWAP: swap bytes in each 4-byte element DATA ·constants<>+0x00(SB)/4, $0x03020100 DATA ·constants<>+0x04(SB)/4, $0x07060504 DATA ·constants<>+0x08(SB)/4, $0x0b0a0908 DATA ·constants<>+0x0c(SB)/4, $0x0f0e0d0c // J0: [j0, j1, j2, j3] DATA ·constants<>+0x10(SB)/4, $0x61707865 DATA ·constants<>+0x14(SB)/4, $0x3320646e DATA ·constants<>+0x18(SB)/4, $0x79622d32 DATA ·constants<>+0x1c(SB)/4, $0x6b206574 #define BSWAP V5 #define J0 V6 #define KEY0 V7 #define KEY1 V8 #define NONCE V9 #define CTR V10 #define M0 V11 #define M1 V12 #define M2 V13 #define M3 V14 #define INC V15 #define X0 V16 #define X1 V17 #define X2 V18 #define X3 V19 #define X4 V20 #define X5 V21 #define X6 V22 #define X7 V23 #define X8 V24 #define X9 V25 #define X10 V26 #define X11 V27 #define X12 V28 #define X13 V29 #define X14 V30 #define X15 V31 #define NUM_ROUNDS 20 #define ROUND4(a0, a1, a2, a3, b0, b1, b2, b3, c0, c1, c2, c3, d0, d1, d2, d3) \ VAF a1, a0, a0 \ VAF b1, b0, b0 \ VAF c1, c0, c0 \ VAF d1, d0, d0 \ VX a0, a2, a2 \ VX b0, b2, b2 \ VX c0, c2, c2 \ VX d0, d2, d2 \ VERLLF $16, a2, a2 \ VERLLF $16, b2, b2 \ VERLLF $16, c2, c2 \ VERLLF $16, d2, d2 \ VAF a2, a3, a3 \ VAF b2, b3, b3 \ VAF c2, c3, c3 \ VAF d2, d3, d3 \ VX a3, a1, a1 \ VX b3, b1, b1 \ VX c3, c1, c1 \ VX d3, d1, d1 \ VERLLF $12, a1, a1 \ VERLLF $12, b1, b1 \ VERLLF $12, c1, c1 \ VERLLF $12, d1, d1 \ VAF a1, a0, a0 \ VAF b1, b0, b0 \ VAF c1, c0, c0 \ VAF d1, d0, d0 \ VX a0, a2, a2 \ VX b0, b2, b2 \ VX c0, c2, c2 \ VX d0, d2, d2 \ VERLLF $8, a2, a2 \ VERLLF $8, b2, b2 \ VERLLF $8, c2, c2 \ VERLLF $8, d2, d2 \ VAF a2, a3, a3 \ VAF b2, b3, b3 \ VAF c2, c3, c3 \ VAF d2, d3, d3 \ VX a3, a1, a1 \ VX b3, b1, b1 \ VX c3, c1, c1 \ VX d3, d1, d1 \ VERLLF $7, a1, a1 \ VERLLF $7, b1, b1 \ VERLLF $7, c1, c1 \ VERLLF $7, d1, d1 #define PERMUTE(mask, v0, v1, v2, v3) \ VPERM v0, v0, mask, v0 \ VPERM v1, v1, mask, v1 \ VPERM v2, v2, mask, v2 \ VPERM v3, v3, mask, v3 #define ADDV(x, v0, v1, v2, v3) \ VAF x, v0, v0 \ VAF x, v1, v1 \ VAF x, v2, v2 \ VAF x, v3, v3 #define XORV(off, dst, src, v0, v1, v2, v3) \ VLM off(src), M0, M3 \ PERMUTE(BSWAP, v0, v1, v2, v3) \ VX v0, M0, M0 \ VX v1, M1, M1 \ VX v2, M2, M2 \ VX v3, M3, M3 \ VSTM M0, M3, off(dst) #define SHUFFLE(a, b, c, d, t, u, v, w) \ VMRHF a, c, t \ // t = {a[0], c[0], a[1], c[1]} VMRHF b, d, u \ // u = {b[0], d[0], b[1], d[1]} VMRLF a, c, v \ // v = {a[2], c[2], a[3], c[3]} VMRLF b, d, w \ // w = {b[2], d[2], b[3], d[3]} VMRHF t, u, a \ // a = {a[0], b[0], c[0], d[0]} VMRLF t, u, b \ // b = {a[1], b[1], c[1], d[1]} VMRHF v, w, c \ // c = {a[2], b[2], c[2], d[2]} VMRLF v, w, d // d = {a[3], b[3], c[3], d[3]} // func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 MOVD $·constants<>(SB), R1 MOVD dst+0(FP), R2 // R2=&dst[0] LMG src+24(FP), R3, R4 // R3=&src[0] R4=len(src) MOVD key+48(FP), R5 // R5=key MOVD nonce+56(FP), R6 // R6=nonce MOVD counter+64(FP), R7 // R7=counter // load BSWAP and J0 VLM (R1), BSWAP, J0 // setup MOVD $95, R0 VLM (R5), KEY0, KEY1 VLL R0, (R6), NONCE VZERO M0 VLEIB $7, $32, M0 VSRLB M0, NONCE, NONCE // initialize counter values VLREPF (R7), CTR VZERO INC VLEIF $1, $1, INC VLEIF $2, $2, INC VLEIF $3, $3, INC VAF INC, CTR, CTR VREPIF $4, INC chacha: VREPF $0, J0, X0 VREPF $1, J0, X1 VREPF $2, J0, X2 VREPF $3, J0, X3 VREPF $0, KEY0, X4 VREPF $1, KEY0, X5 VREPF $2, KEY0, X6 VREPF $3, KEY0, X7 VREPF $0, KEY1, X8 VREPF $1, KEY1, X9 VREPF $2, KEY1, X10 VREPF $3, KEY1, X11 VLR CTR, X12 VREPF $1, NONCE, X13 VREPF $2, NONCE, X14 VREPF $3, NONCE, X15 MOVD $(NUM_ROUNDS/2), R1 loop: ROUND4(X0, X4, X12, X8, X1, X5, X13, X9, X2, X6, X14, X10, X3, X7, X15, X11) ROUND4(X0, X5, X15, X10, X1, X6, X12, X11, X2, X7, X13, X8, X3, X4, X14, X9) ADD $-1, R1 BNE loop // decrement length ADD $-256, R4 // rearrange vectors SHUFFLE(X0, X1, X2, X3, M0, M1, M2, M3) ADDV(J0, X0, X1, X2, X3) SHUFFLE(X4, X5, X6, X7, M0, M1, M2, M3) ADDV(KEY0, X4, X5, X6, X7) SHUFFLE(X8, X9, X10, X11, M0, M1, M2, M3) ADDV(KEY1, X8, X9, X10, X11) VAF CTR, X12, X12 SHUFFLE(X12, X13, X14, X15, M0, M1, M2, M3) ADDV(NONCE, X12, X13, X14, X15) // increment counters VAF INC, CTR, CTR // xor keystream with plaintext XORV(0*64, R2, R3, X0, X4, X8, X12) XORV(1*64, R2, R3, X1, X5, X9, X13) XORV(2*64, R2, R3, X2, X6, X10, X14) XORV(3*64, R2, R3, X3, X7, X11, X15) // increment pointers MOVD $256(R2), R2 MOVD $256(R3), R3 CMPBNE R4, $0, chacha VSTEF $0, CTR, (R7) RET
crypto/chacha20/chacha_s390x.s/0
{ "file_path": "crypto/chacha20/chacha_s390x.s", "repo_id": "crypto", "token_count": 3306 }
4
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package wycheproof import ( "bytes" "crypto/aes" "crypto/cipher" "fmt" "testing" "golang.org/x/crypto/chacha20poly1305" ) func TestAEAD(t *testing.T) { // AeadTestVector type AeadTestVector struct { // additional authenticated data Aad string `json:"aad,omitempty"` // A brief description of the test case Comment string `json:"comment,omitempty"` // the ciphertext (without iv and tag) Ct string `json:"ct,omitempty"` // A list of flags Flags []string `json:"flags,omitempty"` // the nonce Iv string `json:"iv,omitempty"` // the key Key string `json:"key,omitempty"` // the plaintext Msg string `json:"msg,omitempty"` // Test result Result string `json:"result,omitempty"` // the authentication tag Tag string `json:"tag,omitempty"` // Identifier of the test case TcId int `json:"tcId,omitempty"` } // Notes a description of the labels used in the test vectors type Notes struct { } // AeadTestGroup type AeadTestGroup struct { // the IV size in bits IvSize int `json:"ivSize,omitempty"` // the keySize in bits KeySize int `json:"keySize,omitempty"` // the expected size of the tag in bits TagSize int `json:"tagSize,omitempty"` Tests []*AeadTestVector `json:"tests,omitempty"` Type interface{} `json:"type,omitempty"` } // Root type Root struct { // the primitive tested in the test file Algorithm string `json:"algorithm,omitempty"` // the version of the test vectors. GeneratorVersion string `json:"generatorVersion,omitempty"` // additional documentation Header []string `json:"header,omitempty"` // a description of the labels used in the test vectors Notes *Notes `json:"notes,omitempty"` // the number of test vectors in this test NumberOfTests int `json:"numberOfTests,omitempty"` Schema interface{} `json:"schema,omitempty"` TestGroups []*AeadTestGroup `json:"testGroups,omitempty"` } testSealOpen := func(t *testing.T, aead cipher.AEAD, tv *AeadTestVector, recoverBadNonce func()) { defer recoverBadNonce() iv, tag, ct, msg, aad := decodeHex(tv.Iv), decodeHex(tv.Tag), decodeHex(tv.Ct), decodeHex(tv.Msg), decodeHex(tv.Aad) genCT := aead.Seal(nil, iv, msg, aad) genMsg, err := aead.Open(nil, iv, genCT, aad) if err != nil { t.Errorf("failed to decrypt generated ciphertext: %s", err) } if !bytes.Equal(genMsg, msg) { t.Errorf("unexpected roundtripped plaintext: got %x, want %x", genMsg, msg) } ctWithTag := append(ct, tag...) msg2, err := aead.Open(nil, iv, ctWithTag, aad) wantPass := shouldPass(tv.Result, tv.Flags, nil) if !wantPass && err == nil { t.Error("decryption succeeded when it should've failed") } else if wantPass { if err != nil { t.Fatalf("decryption failed: %s", err) } if !bytes.Equal(genCT, ctWithTag) { t.Errorf("generated ciphertext doesn't match expected: got %x, want %x", genCT, ctWithTag) } if !bytes.Equal(msg, msg2) { t.Errorf("decrypted ciphertext doesn't match expected: got %x, want %x", msg2, msg) } } } vectors := map[string]func(*testing.T, []byte) cipher.AEAD{ "aes_gcm_test.json": func(t *testing.T, key []byte) cipher.AEAD { aesCipher, err := aes.NewCipher(key) if err != nil { t.Fatalf("failed to construct cipher: %s", err) } aead, err := cipher.NewGCM(aesCipher) if err != nil { t.Fatalf("failed to construct cipher: %s", err) } return aead }, "chacha20_poly1305_test.json": func(t *testing.T, key []byte) cipher.AEAD { aead, err := chacha20poly1305.New(key) if err != nil { t.Fatalf("failed to construct cipher: %s", err) } return aead }, "xchacha20_poly1305_test.json": func(t *testing.T, key []byte) cipher.AEAD { aead, err := chacha20poly1305.NewX(key) if err != nil { t.Fatalf("failed to construct cipher: %s", err) } return aead }, } for file, cipherInit := range vectors { var root Root readTestVector(t, file, &root) for _, tg := range root.TestGroups { for _, tv := range tg.Tests { testName := fmt.Sprintf("%s #%d", file, tv.TcId) if tv.Comment != "" { testName += fmt.Sprintf(" %s", tv.Comment) } t.Run(testName, func(t *testing.T) { aead := cipherInit(t, decodeHex(tv.Key)) testSealOpen(t, aead, tv, func() { // A bad nonce causes a panic in AEAD.Seal and AEAD.Open, // so should be recovered. Fail the test if it broke for // some other reason. if r := recover(); r != nil { if tg.IvSize/8 == aead.NonceSize() { t.Error("unexpected panic") } } }) }) } } } }
crypto/internal/wycheproof/aead_test.go/0
{ "file_path": "crypto/internal/wycheproof/aead_test.go", "repo_id": "crypto", "token_count": 1997 }
5
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ocsp import ( "bytes" "crypto" "crypto/rand" "crypto/rsa" "crypto/sha1" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/hex" "encoding/pem" "math/big" "reflect" "testing" "time" ) func TestOCSPDecode(t *testing.T) { responseBytes, _ := hex.DecodeString(ocspResponseHex) resp, err := ParseResponse(responseBytes, nil) if err != nil { t.Fatal(err) } // keyHash is the SKID of the issuer of the certificate the OCSP // response is for. keyHash, err := hex.DecodeString("8a747faf85cdee95cd3d9cd0e24614f371351d27") if err != nil { t.Fatal(err) } // serialBytes is the serial number of the certificate the OCSP // response is for. serialBytes, err := hex.DecodeString("f374542e3c7a68360a00000001103462") if err != nil { t.Fatal(err) } expected := Response{ Status: Good, SerialNumber: big.NewInt(0).SetBytes(serialBytes), RevocationReason: Unspecified, ThisUpdate: time.Date(2021, 11, 7, 14, 25, 51, 0, time.UTC), NextUpdate: time.Date(2021, 11, 14, 13, 25, 50, 0, time.UTC), ResponderKeyHash: keyHash, } if !reflect.DeepEqual(resp.ThisUpdate, expected.ThisUpdate) { t.Errorf("resp.ThisUpdate: got %v, want %v", resp.ThisUpdate, expected.ThisUpdate) } if !reflect.DeepEqual(resp.NextUpdate, expected.NextUpdate) { t.Errorf("resp.NextUpdate: got %v, want %v", resp.NextUpdate, expected.NextUpdate) } if resp.Status != expected.Status { t.Errorf("resp.Status: got %d, want %d", resp.Status, expected.Status) } if resp.SerialNumber.Cmp(expected.SerialNumber) != 0 { t.Errorf("resp.SerialNumber: got %x, want %x", resp.SerialNumber, expected.SerialNumber) } if resp.RevocationReason != expected.RevocationReason { t.Errorf("resp.RevocationReason: got %d, want %d", resp.RevocationReason, expected.RevocationReason) } if !bytes.Equal(resp.RawResponderName, expected.RawResponderName) { t.Errorf("resp.RawResponderName: got %x, want %x", resp.RawResponderName, expected.RawResponderName) } if !bytes.Equal(resp.ResponderKeyHash, expected.ResponderKeyHash) { t.Errorf("resp.ResponderKeyHash: got %x, want %x", resp.ResponderKeyHash, expected.ResponderKeyHash) } } func TestOCSPDecodeWithoutCert(t *testing.T) { responseBytes, _ := hex.DecodeString(ocspResponseWithoutCertHex) _, err := ParseResponse(responseBytes, nil) if err != nil { t.Error(err) } } func TestOCSPDecodeWithExtensions(t *testing.T) { responseBytes, _ := hex.DecodeString(ocspResponseWithCriticalExtensionHex) _, err := ParseResponse(responseBytes, nil) if err == nil { t.Error(err) } responseBytes, _ = hex.DecodeString(ocspResponseWithExtensionHex) response, err := ParseResponse(responseBytes, nil) if err != nil { t.Fatal(err) } if len(response.Extensions) != 1 { t.Errorf("len(response.Extensions): got %v, want %v", len(response.Extensions), 1) } extensionBytes := response.Extensions[0].Value expectedBytes, _ := hex.DecodeString(ocspExtensionValueHex) if !bytes.Equal(extensionBytes, expectedBytes) { t.Errorf("response.Extensions[0]: got %x, want %x", extensionBytes, expectedBytes) } } func TestOCSPSignature(t *testing.T) { b, _ := pem.Decode([]byte(GTSRoot)) issuer, err := x509.ParseCertificate(b.Bytes) if err != nil { t.Fatal(err) } response, _ := hex.DecodeString(ocspResponseHex) if _, err := ParseResponse(response, issuer); err != nil { t.Error(err) } } func TestOCSPRequest(t *testing.T) { leafCert, _ := hex.DecodeString(leafCertHex) cert, err := x509.ParseCertificate(leafCert) if err != nil { t.Fatal(err) } issuerCert, _ := hex.DecodeString(issuerCertHex) issuer, err := x509.ParseCertificate(issuerCert) if err != nil { t.Fatal(err) } request, err := CreateRequest(cert, issuer, nil) if err != nil { t.Fatal(err) } expectedBytes, _ := hex.DecodeString(ocspRequestHex) if !bytes.Equal(request, expectedBytes) { t.Errorf("request: got %x, wanted %x", request, expectedBytes) } decodedRequest, err := ParseRequest(expectedBytes) if err != nil { t.Fatal(err) } if decodedRequest.HashAlgorithm != crypto.SHA1 { t.Errorf("request.HashAlgorithm: got %v, want %v", decodedRequest.HashAlgorithm, crypto.SHA1) } var publicKeyInfo struct { Algorithm pkix.AlgorithmIdentifier PublicKey asn1.BitString } _, err = asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo) if err != nil { t.Fatal(err) } h := sha1.New() h.Write(publicKeyInfo.PublicKey.RightAlign()) issuerKeyHash := h.Sum(nil) h.Reset() h.Write(issuer.RawSubject) issuerNameHash := h.Sum(nil) if got := decodedRequest.IssuerKeyHash; !bytes.Equal(got, issuerKeyHash) { t.Errorf("request.IssuerKeyHash: got %x, want %x", got, issuerKeyHash) } if got := decodedRequest.IssuerNameHash; !bytes.Equal(got, issuerNameHash) { t.Errorf("request.IssuerKeyHash: got %x, want %x", got, issuerNameHash) } if got := decodedRequest.SerialNumber; got.Cmp(cert.SerialNumber) != 0 { t.Errorf("request.SerialNumber: got %x, want %x", got, cert.SerialNumber) } marshaledRequest, err := decodedRequest.Marshal() if err != nil { t.Fatal(err) } if bytes.Compare(expectedBytes, marshaledRequest) != 0 { t.Errorf( "Marshaled request doesn't match expected: wanted %x, got %x", expectedBytes, marshaledRequest, ) } } func TestOCSPResponse(t *testing.T) { leafCert, _ := hex.DecodeString(leafCertHex) leaf, err := x509.ParseCertificate(leafCert) if err != nil { t.Fatal(err) } issuerCert, _ := hex.DecodeString(issuerCertHex) issuer, err := x509.ParseCertificate(issuerCert) if err != nil { t.Fatal(err) } responderCert, _ := hex.DecodeString(responderCertHex) responder, err := x509.ParseCertificate(responderCert) if err != nil { t.Fatal(err) } responderPrivateKeyDER, _ := hex.DecodeString(responderPrivateKeyHex) responderPrivateKey, err := x509.ParsePKCS1PrivateKey(responderPrivateKeyDER) if err != nil { t.Fatal(err) } extensionBytes, _ := hex.DecodeString(ocspExtensionValueHex) extensions := []pkix.Extension{ { Id: ocspExtensionOID, Critical: false, Value: extensionBytes, }, } thisUpdate := time.Date(2010, 7, 7, 15, 1, 5, 0, time.UTC) nextUpdate := time.Date(2010, 7, 7, 18, 35, 17, 0, time.UTC) template := Response{ Status: Revoked, SerialNumber: leaf.SerialNumber, ThisUpdate: thisUpdate, NextUpdate: nextUpdate, RevokedAt: thisUpdate, RevocationReason: KeyCompromise, Certificate: responder, ExtraExtensions: extensions, } template.IssuerHash = crypto.MD5 _, err = CreateResponse(issuer, responder, template, responderPrivateKey) if err == nil { t.Fatal("CreateResponse didn't fail with non-valid template.IssuerHash value crypto.MD5") } testCases := []struct { name string issuerHash crypto.Hash }{ {"Zero value", 0}, {"crypto.SHA1", crypto.SHA1}, {"crypto.SHA256", crypto.SHA256}, {"crypto.SHA384", crypto.SHA384}, {"crypto.SHA512", crypto.SHA512}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { template.IssuerHash = tc.issuerHash responseBytes, err := CreateResponse(issuer, responder, template, responderPrivateKey) if err != nil { t.Fatalf("CreateResponse failed: %s", err) } resp, err := ParseResponse(responseBytes, nil) if err != nil { t.Fatalf("ParseResponse failed: %s", err) } if !reflect.DeepEqual(resp.ThisUpdate, template.ThisUpdate) { t.Errorf("resp.ThisUpdate: got %v, want %v", resp.ThisUpdate, template.ThisUpdate) } if !reflect.DeepEqual(resp.NextUpdate, template.NextUpdate) { t.Errorf("resp.NextUpdate: got %v, want %v", resp.NextUpdate, template.NextUpdate) } if !reflect.DeepEqual(resp.RevokedAt, template.RevokedAt) { t.Errorf("resp.RevokedAt: got %v, want %v", resp.RevokedAt, template.RevokedAt) } if !reflect.DeepEqual(resp.Extensions, template.ExtraExtensions) { t.Errorf("resp.Extensions: got %v, want %v", resp.Extensions, template.ExtraExtensions) } delay := time.Since(resp.ProducedAt) if delay < -time.Hour || delay > time.Hour { t.Errorf("resp.ProducedAt: got %s, want close to current time (%s)", resp.ProducedAt, time.Now()) } if resp.Status != template.Status { t.Errorf("resp.Status: got %d, want %d", resp.Status, template.Status) } if resp.SerialNumber.Cmp(template.SerialNumber) != 0 { t.Errorf("resp.SerialNumber: got %x, want %x", resp.SerialNumber, template.SerialNumber) } if resp.RevocationReason != template.RevocationReason { t.Errorf("resp.RevocationReason: got %d, want %d", resp.RevocationReason, template.RevocationReason) } expectedHash := tc.issuerHash if tc.issuerHash == 0 { expectedHash = crypto.SHA1 } if resp.IssuerHash != expectedHash { t.Errorf("resp.IssuerHash: got %d, want %d", resp.IssuerHash, expectedHash) } }) } } func TestErrorResponse(t *testing.T) { responseBytes, _ := hex.DecodeString(errorResponseHex) _, err := ParseResponse(responseBytes, nil) respErr, ok := err.(ResponseError) if !ok { t.Fatalf("expected ResponseError from ParseResponse but got %#v", err) } if respErr.Status != Malformed { t.Fatalf("expected Malformed status from ParseResponse but got %d", respErr.Status) } } func createMultiResp() ([]byte, error) { rawResponderID := asn1.RawValue{ Class: 2, // context-specific Tag: 1, // Name (explicit tag) IsCompound: true, Bytes: []byte{48, 0}, } tbsResponseData := responseData{ Version: 0, RawResponderID: rawResponderID, ProducedAt: time.Now().Truncate(time.Minute).UTC(), } this := time.Now() next := this.Add(time.Hour * 24 * 4) for i := int64(0); i < 5; i++ { tbsResponseData.Responses = append(tbsResponseData.Responses, singleResponse{ CertID: certID{ HashAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: hashOIDs[crypto.SHA1], Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */}, }, NameHash: []byte{1, 2, 3}, IssuerKeyHash: []byte{4, 5, 6}, SerialNumber: big.NewInt(i), }, ThisUpdate: this.UTC(), NextUpdate: next.UTC(), Good: true, }) } tbsResponseDataDER, err := asn1.Marshal(tbsResponseData) if err != nil { return nil, err } k, err := rsa.GenerateKey(rand.Reader, 1024) if err != nil { return nil, err } hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(k.Public(), x509.SHA1WithRSA) if err != nil { return nil, err } responseHash := hashFunc.New() responseHash.Write(tbsResponseDataDER) signature, err := k.Sign(rand.Reader, responseHash.Sum(nil), hashFunc) if err != nil { return nil, err } response := basicResponse{ TBSResponseData: tbsResponseData, SignatureAlgorithm: signatureAlgorithm, Signature: asn1.BitString{ Bytes: signature, BitLength: 8 * len(signature), }, } responseDER, err := asn1.Marshal(response) if err != nil { return nil, err } return asn1.Marshal(responseASN1{ Status: asn1.Enumerated(Success), Response: responseBytes{ ResponseType: idPKIXOCSPBasic, Response: responseDER, }, }) } func TestOCSPDecodeMultiResponse(t *testing.T) { respBytes, err := createMultiResp() if err != nil { t.Fatal(err) } matchingCert := &x509.Certificate{SerialNumber: big.NewInt(3)} resp, err := ParseResponseForCert(respBytes, matchingCert, nil) if err != nil { t.Fatal(err) } if resp.SerialNumber.Cmp(matchingCert.SerialNumber) != 0 { t.Errorf("resp.SerialNumber: got %x, want %x", resp.SerialNumber, 3) } } func TestOCSPDecodeMultiResponseWithoutMatchingCert(t *testing.T) { respBytes, err := createMultiResp() if err != nil { t.Fatal(err) } _, err = ParseResponseForCert(respBytes, &x509.Certificate{SerialNumber: big.NewInt(100)}, nil) want := ParseError("no response matching the supplied certificate") if err != want { t.Errorf("err: got %q, want %q", err, want) } } // This OCSP response was taken from GTS's public OCSP responder. // To recreate: // $ openssl s_client -tls1 -showcerts -servername golang.org -connect golang.org:443 // Copy and paste the first certificate into /tmp/cert.crt and the second into // /tmp/intermediate.crt // Note: depending on what version of openssl you are using, you may need to use the key=value // form for the header argument (i.e. -header host=ocsp.pki.goog) // $ openssl ocsp -issuer /tmp/intermediate.crt -cert /tmp/cert.crt -url http://ocsp.pki.goog/gts1c3 -header host ocsp.pki.goog -resp_text -respout /tmp/ocsp.der // Then hex encode the result: // $ python -c 'print file("/tmp/ocsp.der", "r").read().encode("hex")' const ocspResponseHex = "308201d40a0100a08201cd308201c906092b0601050507300101048201ba308201b630819fa21604148a747faf85cdee95cd3d9cd0e24614f371351d27180f32303231313130373134323535335a30743072304a300906052b0e03021a05000414c72e798addff6134b3baed4742b8bbc6c024076304148a747faf85cdee95cd3d9cd0e24614f371351d27021100f374542e3c7a68360a000000011034628000180f32303231313130373134323535315aa011180f32303231313131343133323535305a300d06092a864886f70d01010b0500038201010087749296e681abe36f2efef047730178ce57e948426959ac62ac5f25b9a63ba3b7f31b9f683aea384d21845c8dda09498f2531c78f3add3969ca4092f31f58ac3c2613719d63b7b9a5260e52814c827f8dd44f4f753b2528bcd03ccec02cdcd4918247f5323f8cfc12cee4ac8f0361587b267019cfd12336db09b04eac59807a480213cfcd9913a3aa2d13a6c88c0a750475a0e991806d94ec0fc9dab599171a43a08e6d935b4a4a13dff9c4a97ad46cef6fb4d61cb2363d788c12d81cce851b478889c2e05d80cd00ae346772a1e7502f011e2ed9be8ef4b194c8b65d6e33671d878cfb30267972075b062ff3d56b51984bf685161afc6e2538dd6e6a23063c" const GTSRoot = `-----BEGIN CERTIFICATE----- MIIFljCCA36gAwIBAgINAgO8U1lrNMcY9QFQZjANBgkqhkiG9w0BAQsFADBHMQsw CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU MBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMjAwODEzMDAwMDQyWhcNMjcwOTMwMDAw MDQyWjBGMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp Y2VzIExMQzETMBEGA1UEAxMKR1RTIENBIDFDMzCCASIwDQYJKoZIhvcNAQEBBQAD ggEPADCCAQoCggEBAPWI3+dijB43+DdCkH9sh9D7ZYIl/ejLa6T/belaI+KZ9hzp kgOZE3wJCor6QtZeViSqejOEH9Hpabu5dOxXTGZok3c3VVP+ORBNtzS7XyV3NzsX lOo85Z3VvMO0Q+sup0fvsEQRY9i0QYXdQTBIkxu/t/bgRQIh4JZCF8/ZK2VWNAcm BA2o/X3KLu/qSHw3TT8An4Pf73WELnlXXPxXbhqW//yMmqaZviXZf5YsBvcRKgKA gOtjGDxQSYflispfGStZloEAoPtR28p3CwvJlk/vcEnHXG0g/Zm0tOLKLnf9LdwL tmsTDIwZKxeWmLnwi/agJ7u2441Rj72ux5uxiZ0CAwEAAaOCAYAwggF8MA4GA1Ud DwEB/wQEAwIBhjAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwEgYDVR0T AQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQUinR/r4XN7pXNPZzQ4kYU83E1HScwHwYD VR0jBBgwFoAU5K8rJnEaK0gnhS9SZizv8IkTcT4waAYIKwYBBQUHAQEEXDBaMCYG CCsGAQUFBzABhhpodHRwOi8vb2NzcC5wa2kuZ29vZy9ndHNyMTAwBggrBgEFBQcw AoYkaHR0cDovL3BraS5nb29nL3JlcG8vY2VydHMvZ3RzcjEuZGVyMDQGA1UdHwQt MCswKaAnoCWGI2h0dHA6Ly9jcmwucGtpLmdvb2cvZ3RzcjEvZ3RzcjEuY3JsMFcG A1UdIARQME4wOAYKKwYBBAHWeQIFAzAqMCgGCCsGAQUFBwIBFhxodHRwczovL3Br aS5nb29nL3JlcG9zaXRvcnkvMAgGBmeBDAECATAIBgZngQwBAgIwDQYJKoZIhvcN AQELBQADggIBAIl9rCBcDDy+mqhXlRu0rvqrpXJxtDaV/d9AEQNMwkYUuxQkq/BQ cSLbrcRuf8/xam/IgxvYzolfh2yHuKkMo5uhYpSTld9brmYZCwKWnvy15xBpPnrL RklfRuFBsdeYTWU0AIAaP0+fbH9JAIFTQaSSIYKCGvGjRFsqUBITTcFTNvNCCK9U +o53UxtkOCcXCb1YyRt8OS1b887U7ZfbFAO/CVMkH8IMBHmYJvJh8VNS/UKMG2Yr PxWhu//2m+OBmgEGcYk1KCTd4b3rGS3hSMs9WYNRtHTGnXzGsYZbr8w0xNPM1IER lQCh9BIiAfq0g3GvjLeMcySsN1PCAJA/Ef5c7TaUEDu9Ka7ixzpiO2xj2YC/WXGs Yye5TBeg2vZzFb8q3o/zpWwygTMD0IZRcZk0upONXbVRWPeyk+gB9lm+cZv9TSjO z23HFtz30dZGm6fKa+l3D/2gthsjgx0QGtkJAITgRNOidSOzNIb2ILCkXhAd4FJG AJ2xDx8hcFH1mt0G/FX0Kw4zd8NLQsLxdxP8c4CU6x+7Nz/OAipmsHMdMqUybDKw juDEI/9bfU1lcKwrmz3O2+BtjjKAvpafkmO8l7tdufThcV4q5O8DIrGKZTqPwJNl 1IXNDw9bg1kWRxYtnCQ6yICmJhSFm/Y3m6xv+cXDBlHz4n/FsRC6UfTd -----END CERTIFICATE-----` const startComHex = "308206343082041ca003020102020118300d06092a864886f70d0101050500307d310b30" + "0906035504061302494c31163014060355040a130d5374617274436f6d204c74642e312b" + "3029060355040b1322536563757265204469676974616c20436572746966696361746520" + "5369676e696e6731293027060355040313205374617274436f6d20436572746966696361" + "74696f6e20417574686f72697479301e170d3037313032343230353431375a170d313731" + "3032343230353431375a30818c310b300906035504061302494c31163014060355040a13" + "0d5374617274436f6d204c74642e312b3029060355040b13225365637572652044696769" + "74616c204365727469666963617465205369676e696e67313830360603550403132f5374" + "617274436f6d20436c6173732031205072696d61727920496e7465726d65646961746520" + "53657276657220434130820122300d06092a864886f70d01010105000382010f00308201" + "0a0282010100b689c6acef09527807ac9263d0f44418188480561f91aee187fa3250b4d3" + "4706f0e6075f700e10f71dc0ce103634855a0f92ac83c6ac58523fba38e8fce7a724e240" + "a60876c0926e9e2a6d4d3f6e61200adb59ded27d63b33e46fefa215118d7cd30a6ed076e" + "3b7087b4f9faebee823c056f92f7a4dc0a301e9373fe07cad75f809d225852ae06da8b87" + "2369b0e42ad8ea83d2bdf371db705a280faf5a387045123f304dcd3baf17e50fcba0a95d" + "48aab16150cb34cd3c5cc30be810c08c9bf0030362feb26c3e720eee1c432ac9480e5739" + "c43121c810c12c87fe5495521f523c31129b7fe7c0a0a559d5e28f3ef0d5a8e1d77031a9" + "c4b3cfaf6d532f06f4a70203010001a38201ad308201a9300f0603551d130101ff040530" + "030101ff300e0603551d0f0101ff040403020106301d0603551d0e04160414eb4234d098" + "b0ab9ff41b6b08f7cc642eef0e2c45301f0603551d230418301680144e0bef1aa4405ba5" + "17698730ca346843d041aef2306606082b06010505070101045a3058302706082b060105" + "05073001861b687474703a2f2f6f6373702e737461727473736c2e636f6d2f6361302d06" + "082b060105050730028621687474703a2f2f7777772e737461727473736c2e636f6d2f73" + "667363612e637274305b0603551d1f045430523027a025a0238621687474703a2f2f7777" + "772e737461727473736c2e636f6d2f73667363612e63726c3027a025a023862168747470" + "3a2f2f63726c2e737461727473736c2e636f6d2f73667363612e63726c3081800603551d" + "20047930773075060b2b0601040181b5370102013066302e06082b060105050702011622" + "687474703a2f2f7777772e737461727473736c2e636f6d2f706f6c6963792e7064663034" + "06082b060105050702011628687474703a2f2f7777772e737461727473736c2e636f6d2f" + "696e7465726d6564696174652e706466300d06092a864886f70d01010505000382020100" + "2109493ea5886ee00b8b48da314d8ff75657a2e1d36257e9b556f38545753be5501f048b" + "e6a05a3ee700ae85d0fbff200364cbad02e1c69172f8a34dd6dee8cc3fa18aa2e37c37a7" + "c64f8f35d6f4d66e067bdd21d9cf56ffcb302249fe8904f385e5aaf1e71fe875904dddf9" + "46f74234f745580c110d84b0c6da5d3ef9019ee7e1da5595be741c7bfc4d144fac7e5547" + "7d7bf4a50d491e95e8f712c1ccff76a62547d0f37535be97b75816ebaa5c786fec5330af" + "ea044dcca902e3f0b60412f630b1113d904e5664d7dc3c435f7339ef4baf87ebf6fe6888" + "4472ead207c669b0c1a18bef1749d761b145485f3b2021e95bb2ccf4d7e931f50b15613b" + "7a94e3ebd9bc7f94ae6ae3626296a8647cb887f399327e92a252bebbf865cfc9f230fc8b" + "c1c2a696d75f89e15c3480f58f47072fb491bfb1a27e5f4b5ad05b9f248605515a690365" + "434971c5e06f94346bf61bd8a9b04c7e53eb8f48dfca33b548fa364a1a53a6330cd089cd" + "4915cd89313c90c072d7654b52358a461144b93d8e2865a63e799e5c084429adb035112e" + "214eb8d2e7103e5d8483b3c3c2e4d2c6fd094b7409ddf1b3d3193e800da20b19f038e7c5" + "c2afe223db61e29d5c6e2089492e236ab262c145b49faf8ba7f1223bf87de290d07a19fb" + "4a4ce3d27d5f4a8303ed27d6239e6b8db459a2d9ef6c8229dd75193c3f4c108defbb7527" + "d2ae83a7a8ce5ba7" const ocspResponseWithoutCertHex = "308201d40a0100a08201cd308201c906092b0601050507300101048201ba3082" + "01b630819fa2160414884451ff502a695e2d88f421bad90cf2cecbea7c180f3230313330" + "3631383037323434335a30743072304a300906052b0e03021a0500041448b60d38238df8" + "456e4ee5843ea394111802979f0414884451ff502a695e2d88f421bad90cf2cecbea7c02" + "1100f78b13b946fc9635d8ab49de9d2148218000180f3230313330363138303732343433" + "5aa011180f32303133303632323037323434335a300d06092a864886f70d010105050003" + "82010100103e18b3d297a5e7a6c07a4fc52ac46a15c0eba96f3be17f0ffe84de5b8c8e05" + "5a8f577586a849dc4abd6440eb6fedde4622451e2823c1cbf3558b4e8184959c9fe96eff" + "8bc5f95866c58c6d087519faabfdae37e11d9874f1bc0db292208f645dd848185e4dd38b" + "6a8547dfa7b74d514a8470015719064d35476b95bebb03d4d2845c5ca15202d2784878f2" + "0f904c24f09736f044609e9c271381713400e563023d212db422236440c6f377bbf24b2b" + "9e7dec8698e36a8df68b7592ad3489fb2937afb90eb85d2aa96b81c94c25057dbd4759d9" + "20a1a65c7f0b6427a224b3c98edd96b9b61f706099951188b0289555ad30a216fb774651" + "5a35fca2e054dfa8" // PKIX nonce extension var ocspExtensionOID = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1, 2} var ocspExtensionValueHex = "0403000000" const ocspResponseWithCriticalExtensionHex = "308204fe0a0100a08204f7308204f306092b0601050507300101048204e4308204e03081" + "dba003020100a11b3019311730150603550403130e4f43535020526573706f6e64657218" + "0f32303136303130343137303130305a3081a53081a23049300906052b0e03021a050004" + "14c0fe0278fc99188891b3f212e9c7e1b21ab7bfc004140dfc1df0a9e0f01ce7f2b21317" + "7e6f8d157cd4f60210017f77deb3bcbb235d44ccc7dba62e72a116180f32303130303730" + "373135303130355aa0030a0101180f32303130303730373135303130355aa011180f3230" + "3130303730373138333531375aa1193017301506092b06010505073001020101ff040504" + "03000000300d06092a864886f70d01010b0500038201010031c730ca60a7a0d92d8e4010" + "911b469de95b4d27e89de6537552436237967694f76f701cf6b45c932bd308bca4a8d092" + "5c604ba94796903091d9e6c000178e72c1f0a24a277dd262835af5d17d3f9d7869606c9f" + "e7c8e708a41645699895beee38bfa63bb46296683761c5d1d65439b8ab868dc3017c9eeb" + "b70b82dbf3a31c55b457d48bb9e82b335ed49f445042eaf606b06a3e0639824924c89c63" + "eccddfe85e6694314138b2536f5e15e07085d0f6e26d4b2f8244bab0d70de07283ac6384" + "a0501fc3dea7cf0adfd4c7f34871080900e252ddc403e3f0265f2a704af905d3727504ed" + "28f3214a219d898a022463c78439799ca81c8cbafdbcec34ea937cd6a08202ea308202e6" + "308202e2308201caa003020102020101300d06092a864886f70d01010b05003019311730" + "150603550403130e4f43535020526573706f6e646572301e170d31353031333031353530" + "33335a170d3136303133303135353033335a3019311730150603550403130e4f43535020" + "526573706f6e64657230820122300d06092a864886f70d01010105000382010f00308201" + "0a0282010100e8155f2d3e6f2e8d14c62a788bd462f9f844e7a6977c83ef1099f0f6616e" + "c5265b56f356e62c5400f0b06a2e7945a82752c636df32a895152d6074df1701dc6ccfbc" + "bec75a70bd2b55ae2be7e6cad3b5fd4cd5b7790ab401a436d3f5f346074ffde8a99d5b72" + "3350f0a112076614b12ef79c78991b119453445acf2416ab0046b540db14c9fc0f27b898" + "9ad0f63aa4b8aefc91aa8a72160c36307c60fec78a93d3fddf4259902aa77e7332971c7d" + "285b6a04f648993c6922a3e9da9adf5f81508c3228791843e5d49f24db2f1290bafd97e6" + "55b1049a199f652cd603c4fafa330c390b0da78fbbc67e8fa021cbd74eb96222b12ace31" + "a77dcf920334dc94581b0203010001a3353033300e0603551d0f0101ff04040302078030" + "130603551d25040c300a06082b06010505070309300c0603551d130101ff04023000300d" + "06092a864886f70d01010b05000382010100718012761b5063e18f0dc44644d8e6ab8612" + "31c15fd5357805425d82aec1de85bf6d3e30fce205e3e3b8b795bbe52e40a439286d2288" + "9064f4aeeb150359b9425f1da51b3a5c939018555d13ac42c565a0603786a919328f3267" + "09dce52c22ad958ecb7873b9771d1148b1c4be2efe80ba868919fc9f68b6090c2f33c156" + "d67156e42766a50b5d51e79637b7e58af74c2a951b1e642fa7741fec982cc937de37eff5" + "9e2005d5939bfc031589ca143e6e8ab83f40ee08cc20a6b4a95a318352c28d18528dcaf9" + "66705de17afa19d6e8ae91ddf33179d16ebb6ac2c69cae8373d408ebf8c55308be6c04d9" + "3a25439a94299a65a709756c7a3e568be049d5c38839" const ocspResponseWithExtensionHex = "308204fb0a0100a08204f4308204f006092b0601050507300101048204e1308204dd3081" + "d8a003020100a11b3019311730150603550403130e4f43535020526573706f6e64657218" + "0f32303136303130343136353930305a3081a230819f3049300906052b0e03021a050004" + "14c0fe0278fc99188891b3f212e9c7e1b21ab7bfc004140dfc1df0a9e0f01ce7f2b21317" + "7e6f8d157cd4f60210017f77deb3bcbb235d44ccc7dba62e72a116180f32303130303730" + "373135303130355aa0030a0101180f32303130303730373135303130355aa011180f3230" + "3130303730373138333531375aa1163014301206092b0601050507300102040504030000" + "00300d06092a864886f70d01010b05000382010100c09a33e0b2324c852421bb83f85ac9" + "9113f5426012bd2d2279a8166e9241d18a33c870894250622ffc7ed0c4601b16d624f90b" + "779265442cdb6868cf40ab304ab4b66e7315ed02cf663b1601d1d4751772b31bc299db23" + "9aebac78ed6797c06ed815a7a8d18d63cfbb609cafb47ec2e89e37db255216eb09307848" + "d01be0a3e943653c78212b96ff524b74c9ec456b17cdfb950cc97645c577b2e09ff41dde" + "b03afb3adaa381cc0f7c1d95663ef22a0f72f2c45613ae8e2b2d1efc96e8463c7d1d8a1d" + "7e3b35df8fe73a301fc3f804b942b2b3afa337ff105fc1462b7b1c1d75eb4566c8665e59" + "f80393b0adbf8004ff6c3327ed34f007cb4a3348a7d55e06e3a08202ea308202e6308202" + "e2308201caa003020102020101300d06092a864886f70d01010b05003019311730150603" + "550403130e4f43535020526573706f6e646572301e170d3135303133303135353033335a" + "170d3136303133303135353033335a3019311730150603550403130e4f43535020526573" + "706f6e64657230820122300d06092a864886f70d01010105000382010f003082010a0282" + "010100e8155f2d3e6f2e8d14c62a788bd462f9f844e7a6977c83ef1099f0f6616ec5265b" + "56f356e62c5400f0b06a2e7945a82752c636df32a895152d6074df1701dc6ccfbcbec75a" + "70bd2b55ae2be7e6cad3b5fd4cd5b7790ab401a436d3f5f346074ffde8a99d5b723350f0" + "a112076614b12ef79c78991b119453445acf2416ab0046b540db14c9fc0f27b8989ad0f6" + "3aa4b8aefc91aa8a72160c36307c60fec78a93d3fddf4259902aa77e7332971c7d285b6a" + "04f648993c6922a3e9da9adf5f81508c3228791843e5d49f24db2f1290bafd97e655b104" + "9a199f652cd603c4fafa330c390b0da78fbbc67e8fa021cbd74eb96222b12ace31a77dcf" + "920334dc94581b0203010001a3353033300e0603551d0f0101ff04040302078030130603" + "551d25040c300a06082b06010505070309300c0603551d130101ff04023000300d06092a" + "864886f70d01010b05000382010100718012761b5063e18f0dc44644d8e6ab861231c15f" + "d5357805425d82aec1de85bf6d3e30fce205e3e3b8b795bbe52e40a439286d22889064f4" + "aeeb150359b9425f1da51b3a5c939018555d13ac42c565a0603786a919328f326709dce5" + "2c22ad958ecb7873b9771d1148b1c4be2efe80ba868919fc9f68b6090c2f33c156d67156" + "e42766a50b5d51e79637b7e58af74c2a951b1e642fa7741fec982cc937de37eff59e2005" + "d5939bfc031589ca143e6e8ab83f40ee08cc20a6b4a95a318352c28d18528dcaf966705d" + "e17afa19d6e8ae91ddf33179d16ebb6ac2c69cae8373d408ebf8c55308be6c04d93a2543" + "9a94299a65a709756c7a3e568be049d5c38839" const ocspRequestHex = "3051304f304d304b3049300906052b0e03021a05000414c0fe0278fc99188891b3f212e9" + "c7e1b21ab7bfc004140dfc1df0a9e0f01ce7f2b213177e6f8d157cd4f60210017f77deb3" + "bcbb235d44ccc7dba62e72" const leafCertHex = "308203c830820331a0030201020210017f77deb3bcbb235d44ccc7dba62e72300d06092a" + "864886f70d01010505003081ba311f301d060355040a1316566572695369676e20547275" + "7374204e6574776f726b31173015060355040b130e566572695369676e2c20496e632e31" + "333031060355040b132a566572695369676e20496e7465726e6174696f6e616c20536572" + "766572204341202d20436c617373203331493047060355040b13407777772e7665726973" + "69676e2e636f6d2f43505320496e636f72702e6279205265662e204c494142494c495459" + "204c54442e286329393720566572695369676e301e170d3132303632313030303030305a" + "170d3133313233313233353935395a3068310b3009060355040613025553311330110603" + "550408130a43616c69666f726e6961311230100603550407130950616c6f20416c746f31" + "173015060355040a130e46616365626f6f6b2c20496e632e311730150603550403140e2a" + "2e66616365626f6f6b2e636f6d30819f300d06092a864886f70d010101050003818d0030" + "818902818100ae94b171e2deccc1693e051063240102e0689ae83c39b6b3e74b97d48d7b" + "23689100b0b496ee62f0e6d356bcf4aa0f50643402f5d1766aa972835a7564723f39bbef" + "5290ded9bcdbf9d3d55dfad23aa03dc604c54d29cf1d4b3bdbd1a809cfae47b44c7eae17" + "c5109bee24a9cf4a8d911bb0fd0415ae4c3f430aa12a557e2ae10203010001a382011e30" + "82011a30090603551d130402300030440603551d20043d303b3039060b6086480186f845" + "01071703302a302806082b06010505070201161c68747470733a2f2f7777772e76657269" + "7369676e2e636f6d2f727061303c0603551d1f043530333031a02fa02d862b687474703a" + "2f2f535652496e746c2d63726c2e766572697369676e2e636f6d2f535652496e746c2e63" + "726c301d0603551d250416301406082b0601050507030106082b06010505070302300b06" + "03551d0f0404030205a0303406082b0601050507010104283026302406082b0601050507" + "30018618687474703a2f2f6f6373702e766572697369676e2e636f6d30270603551d1104" + "20301e820e2a2e66616365626f6f6b2e636f6d820c66616365626f6f6b2e636f6d300d06" + "092a864886f70d0101050500038181005b6c2b75f8ed30aa51aad36aba595e555141951f" + "81a53b447910ac1f76ff78fc2781616b58f3122afc1c87010425e9ed43df1a7ba6498060" + "67e2688af03db58c7df4ee03309a6afc247ccb134dc33e54c6bc1d5133a532a73273b1d7" + "9cadc08e7e1a83116d34523340b0305427a21742827c98916698ee7eaf8c3bdd71700817" const issuerCertHex = "30820383308202eca003020102021046fcebbab4d02f0f926098233f93078f300d06092a" + "864886f70d0101050500305f310b300906035504061302555331173015060355040a130e" + "566572695369676e2c20496e632e31373035060355040b132e436c617373203320507562" + "6c6963205072696d6172792043657274696669636174696f6e20417574686f7269747930" + "1e170d3937303431373030303030305a170d3136313032343233353935395a3081ba311f" + "301d060355040a1316566572695369676e205472757374204e6574776f726b3117301506" + "0355040b130e566572695369676e2c20496e632e31333031060355040b132a5665726953" + "69676e20496e7465726e6174696f6e616c20536572766572204341202d20436c61737320" + "3331493047060355040b13407777772e766572697369676e2e636f6d2f43505320496e63" + "6f72702e6279205265662e204c494142494c495459204c54442e28632939372056657269" + "5369676e30819f300d06092a864886f70d010101050003818d0030818902818100d88280" + "e8d619027d1f85183925a2652be1bfd405d3bce6363baaf04c6c5bb6e7aa3c734555b2f1" + "bdea9742ed9a340a15d4a95cf54025ddd907c132b2756cc4cabba3fe56277143aa63f530" + "3e9328e5faf1093bf3b74d4e39f75c495ab8c11dd3b28afe70309542cbfe2b518b5a3c3a" + "f9224f90b202a7539c4f34e7ab04b27b6f0203010001a381e33081e0300f0603551d1304" + "0830060101ff02010030440603551d20043d303b3039060b6086480186f8450107010130" + "2a302806082b06010505070201161c68747470733a2f2f7777772e766572697369676e2e" + "636f6d2f43505330340603551d25042d302b06082b0601050507030106082b0601050507" + "030206096086480186f8420401060a6086480186f845010801300b0603551d0f04040302" + "0106301106096086480186f842010104040302010630310603551d1f042a30283026a024" + "a0228620687474703a2f2f63726c2e766572697369676e2e636f6d2f706361332e63726c" + "300d06092a864886f70d010105050003818100408e4997968a73dd8e4def3e61b7caa062" + "adf40e0abb753de26ed82cc7bff4b98c369bcaa2d09c724639f6a682036511c4bcbf2da6" + "f5d93b0ab598fab378b91ef22b4c62d5fdb27a1ddf33fd73f9a5d82d8c2aead1fcb028b6" + "e94948134b838a1b487b24f738de6f4154b8ab576b06dfc7a2d4a9f6f136628088f28b75" + "d68071" // Key and certificate for the OCSP responder were not taken from the Thawte // responder, since CreateResponse requires that we have the private key. // Instead, they were generated randomly. const responderPrivateKeyHex = "308204a40201000282010100e8155f2d3e6f2e8d14c62a788bd462f9f844e7a6977c83ef" + "1099f0f6616ec5265b56f356e62c5400f0b06a2e7945a82752c636df32a895152d6074df" + "1701dc6ccfbcbec75a70bd2b55ae2be7e6cad3b5fd4cd5b7790ab401a436d3f5f346074f" + "fde8a99d5b723350f0a112076614b12ef79c78991b119453445acf2416ab0046b540db14" + "c9fc0f27b8989ad0f63aa4b8aefc91aa8a72160c36307c60fec78a93d3fddf4259902aa7" + "7e7332971c7d285b6a04f648993c6922a3e9da9adf5f81508c3228791843e5d49f24db2f" + "1290bafd97e655b1049a199f652cd603c4fafa330c390b0da78fbbc67e8fa021cbd74eb9" + "6222b12ace31a77dcf920334dc94581b02030100010282010100bcf0b93d7238bda329a8" + "72e7149f61bcb37c154330ccb3f42a85c9002c2e2bdea039d77d8581cd19bed94078794e" + "56293d601547fc4bf6a2f9002fe5772b92b21b254403b403585e3130cc99ccf08f0ef81a" + "575b38f597ba4660448b54f44bfbb97072b5a2bf043bfeca828cf7741d13698e3f38162b" + "679faa646b82abd9a72c5c7d722c5fc577a76d2c2daac588accad18516d1bbad10b0dfa2" + "05cfe246b59e28608a43942e1b71b0c80498075121de5b900d727c31c42c78cf1db5c0aa" + "5b491e10ea4ed5c0962aaf2ae025dd81fa4ce490d9d6b4a4465411d8e542fc88617e5695" + "1aa4fc8ea166f2b4d0eb89ef17f2b206bd5f1014bf8fe0e71fe62f2cccf102818100f2dc" + "ddf878d553286daad68bac4070a82ffec3dc4666a2750f47879eec913f91836f1d976b60" + "daf9356e078446dafab5bd2e489e5d64f8572ba24a4ba4f3729b5e106c4dd831cc2497a7" + "e6c7507df05cb64aeb1bbc81c1e340d58b5964cf39cff84ea30c29ec5d3f005ee1362698" + "07395037955955655292c3e85f6187fa1f9502818100f4a33c102630840705f8c778a47b" + "87e8da31e68809af981ac5e5999cf1551685d761cdf0d6520361b99aebd5777a940fa64d" + "327c09fa63746fbb3247ec73a86edf115f1fe5c83598db803881ade71c33c6e956118345" + "497b98b5e07bb5be75971465ec78f2f9467e1b74956ca9d4c7c3e314e742a72d8b33889c" + "6c093a466cef0281801d3df0d02124766dd0be98349b19eb36a508c4e679e793ba0a8bef" + "4d786888c1e9947078b1ea28938716677b4ad8c5052af12eb73ac194915264a913709a0b" + "7b9f98d4a18edd781a13d49899f91c20dbd8eb2e61d991ba19b5cdc08893f5cb9d39e5a6" + "0629ea16d426244673b1b3ee72bd30e41fac8395acac40077403de5efd028180050731dd" + "d71b1a2b96c8d538ba90bb6b62c8b1c74c03aae9a9f59d21a7a82b0d572ef06fa9c807bf" + "c373d6b30d809c7871df96510c577421d9860c7383fda0919ece19996b3ca13562159193" + "c0c246471e287f975e8e57034e5136aaf44254e2650def3d51292474c515b1588969112e" + "0a85cc77073e9d64d2c2fc497844284b02818100d71d63eabf416cf677401ebf965f8314" + "120b568a57dd3bd9116c629c40dc0c6948bab3a13cc544c31c7da40e76132ef5dd3f7534" + "45a635930c74326ae3df0edd1bfb1523e3aa259873ac7cf1ac31151ec8f37b528c275622" + "48f99b8bed59fd4da2576aa6ee20d93a684900bf907e80c66d6e2261ae15e55284b4ed9d" + "6bdaa059" const responderCertHex = "308202e2308201caa003020102020101300d06092a864886f70d01010b05003019311730" + "150603550403130e4f43535020526573706f6e646572301e170d31353031333031353530" + "33335a170d3136303133303135353033335a3019311730150603550403130e4f43535020" + "526573706f6e64657230820122300d06092a864886f70d01010105000382010f00308201" + "0a0282010100e8155f2d3e6f2e8d14c62a788bd462f9f844e7a6977c83ef1099f0f6616e" + "c5265b56f356e62c5400f0b06a2e7945a82752c636df32a895152d6074df1701dc6ccfbc" + "bec75a70bd2b55ae2be7e6cad3b5fd4cd5b7790ab401a436d3f5f346074ffde8a99d5b72" + "3350f0a112076614b12ef79c78991b119453445acf2416ab0046b540db14c9fc0f27b898" + "9ad0f63aa4b8aefc91aa8a72160c36307c60fec78a93d3fddf4259902aa77e7332971c7d" + "285b6a04f648993c6922a3e9da9adf5f81508c3228791843e5d49f24db2f1290bafd97e6" + "55b1049a199f652cd603c4fafa330c390b0da78fbbc67e8fa021cbd74eb96222b12ace31" + "a77dcf920334dc94581b0203010001a3353033300e0603551d0f0101ff04040302078030" + "130603551d25040c300a06082b06010505070309300c0603551d130101ff04023000300d" + "06092a864886f70d01010b05000382010100718012761b5063e18f0dc44644d8e6ab8612" + "31c15fd5357805425d82aec1de85bf6d3e30fce205e3e3b8b795bbe52e40a439286d2288" + "9064f4aeeb150359b9425f1da51b3a5c939018555d13ac42c565a0603786a919328f3267" + "09dce52c22ad958ecb7873b9771d1148b1c4be2efe80ba868919fc9f68b6090c2f33c156" + "d67156e42766a50b5d51e79637b7e58af74c2a951b1e642fa7741fec982cc937de37eff5" + "9e2005d5939bfc031589ca143e6e8ab83f40ee08cc20a6b4a95a318352c28d18528dcaf9" + "66705de17afa19d6e8ae91ddf33179d16ebb6ac2c69cae8373d408ebf8c55308be6c04d9" + "3a25439a94299a65a709756c7a3e568be049d5c38839" const errorResponseHex = "30030a0101"
crypto/ocsp/ocsp_test.go/0
{ "file_path": "crypto/ocsp/ocsp_test.go", "repo_id": "crypto", "token_count": 18098 }
6
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "crypto" "crypto/rand" "io" "time" ) // Config collects a number of parameters along with sensible defaults. // A nil *Config is valid and results in all default values. type Config struct { // Rand provides the source of entropy. // If nil, the crypto/rand Reader is used. Rand io.Reader // DefaultHash is the default hash function to be used. // If zero, SHA-256 is used. DefaultHash crypto.Hash // DefaultCipher is the cipher to be used. // If zero, AES-128 is used. DefaultCipher CipherFunction // Time returns the current time as the number of seconds since the // epoch. If Time is nil, time.Now is used. Time func() time.Time // DefaultCompressionAlgo is the compression algorithm to be // applied to the plaintext before encryption. If zero, no // compression is done. DefaultCompressionAlgo CompressionAlgo // CompressionConfig configures the compression settings. CompressionConfig *CompressionConfig // S2KCount is only used for symmetric encryption. It // determines the strength of the passphrase stretching when // the said passphrase is hashed to produce a key. S2KCount // should be between 1024 and 65011712, inclusive. If Config // is nil or S2KCount is 0, the value 65536 used. Not all // values in the above range can be represented. S2KCount will // be rounded up to the next representable value if it cannot // be encoded exactly. When set, it is strongly encrouraged to // use a value that is at least 65536. See RFC 4880 Section // 3.7.1.3. S2KCount int // RSABits is the number of bits in new RSA keys made with NewEntity. // If zero, then 2048 bit keys are created. RSABits int } func (c *Config) Random() io.Reader { if c == nil || c.Rand == nil { return rand.Reader } return c.Rand } func (c *Config) Hash() crypto.Hash { if c == nil || uint(c.DefaultHash) == 0 { return crypto.SHA256 } return c.DefaultHash } func (c *Config) Cipher() CipherFunction { if c == nil || uint8(c.DefaultCipher) == 0 { return CipherAES128 } return c.DefaultCipher } func (c *Config) Now() time.Time { if c == nil || c.Time == nil { return time.Now() } return c.Time() } func (c *Config) Compression() CompressionAlgo { if c == nil { return CompressionNone } return c.DefaultCompressionAlgo } func (c *Config) PasswordHashIterations() int { if c == nil || c.S2KCount == 0 { return 0 } return c.S2KCount }
crypto/openpgp/packet/config.go/0
{ "file_path": "crypto/openpgp/packet/config.go", "repo_id": "crypto", "token_count": 814 }
7
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "encoding/hex" "testing" "time" ) var pubKeyV3Test = struct { hexFingerprint string creationTime time.Time pubKeyAlgo PublicKeyAlgorithm keyId uint64 keyIdString string keyIdShort string }{ "103BECF5BD1E837C89D19E98487767F7", time.Unix(779753634, 0), PubKeyAlgoRSA, 0xDE0F188A5DA5E3C9, "DE0F188A5DA5E3C9", "5DA5E3C9"} func TestPublicKeyV3Read(t *testing.T) { i, test := 0, pubKeyV3Test packet, err := Read(v3KeyReader(t)) if err != nil { t.Fatalf("#%d: Read error: %s", i, err) } pk, ok := packet.(*PublicKeyV3) if !ok { t.Fatalf("#%d: failed to parse, got: %#v", i, packet) } if pk.PubKeyAlgo != test.pubKeyAlgo { t.Errorf("#%d: bad public key algorithm got:%x want:%x", i, pk.PubKeyAlgo, test.pubKeyAlgo) } if !pk.CreationTime.Equal(test.creationTime) { t.Errorf("#%d: bad creation time got:%v want:%v", i, pk.CreationTime, test.creationTime) } expectedFingerprint, _ := hex.DecodeString(test.hexFingerprint) if !bytes.Equal(expectedFingerprint, pk.Fingerprint[:]) { t.Errorf("#%d: bad fingerprint got:%x want:%x", i, pk.Fingerprint[:], expectedFingerprint) } if pk.KeyId != test.keyId { t.Errorf("#%d: bad keyid got:%x want:%x", i, pk.KeyId, test.keyId) } if g, e := pk.KeyIdString(), test.keyIdString; g != e { t.Errorf("#%d: bad KeyIdString got:%q want:%q", i, g, e) } if g, e := pk.KeyIdShortString(), test.keyIdShort; g != e { t.Errorf("#%d: bad KeyIdShortString got:%q want:%q", i, g, e) } } func TestPublicKeyV3Serialize(t *testing.T) { //for i, test := range pubKeyV3Tests { i := 0 packet, err := Read(v3KeyReader(t)) if err != nil { t.Fatalf("#%d: Read error: %s", i, err) } pk, ok := packet.(*PublicKeyV3) if !ok { t.Fatalf("#%d: failed to parse, got: %#v", i, packet) } var serializeBuf bytes.Buffer if err = pk.Serialize(&serializeBuf); err != nil { t.Fatalf("#%d: failed to serialize: %s", i, err) } if packet, err = Read(bytes.NewBuffer(serializeBuf.Bytes())); err != nil { t.Fatalf("#%d: Read error (from serialized data): %s", i, err) } if pk, ok = packet.(*PublicKeyV3); !ok { t.Fatalf("#%d: failed to parse serialized data, got: %#v", i, packet) } }
crypto/openpgp/packet/public_key_v3_test.go/0
{ "file_path": "crypto/openpgp/packet/public_key_v3_test.go", "repo_id": "crypto", "token_count": 1058 }
8
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package s2k implements the various OpenPGP string-to-key transforms as // specified in RFC 4800 section 3.7.1. // // Deprecated: this package is unmaintained except for security fixes. New // applications should consider a more focused, modern alternative to OpenPGP // for their specific task. If you are required to interoperate with OpenPGP // systems and need a maintained package, consider a community fork. // See https://golang.org/issue/44226. package s2k import ( "crypto" "hash" "io" "strconv" "golang.org/x/crypto/openpgp/errors" ) // Config collects configuration parameters for s2k key-stretching // transformatioms. A nil *Config is valid and results in all default // values. Currently, Config is used only by the Serialize function in // this package. type Config struct { // Hash is the default hash function to be used. If // nil, SHA1 is used. Hash crypto.Hash // S2KCount is only used for symmetric encryption. It // determines the strength of the passphrase stretching when // the said passphrase is hashed to produce a key. S2KCount // should be between 1024 and 65011712, inclusive. If Config // is nil or S2KCount is 0, the value 65536 used. Not all // values in the above range can be represented. S2KCount will // be rounded up to the next representable value if it cannot // be encoded exactly. When set, it is strongly encrouraged to // use a value that is at least 65536. See RFC 4880 Section // 3.7.1.3. S2KCount int } func (c *Config) hash() crypto.Hash { if c == nil || uint(c.Hash) == 0 { // SHA1 is the historical default in this package. return crypto.SHA1 } return c.Hash } func (c *Config) encodedCount() uint8 { if c == nil || c.S2KCount == 0 { return 96 // The common case. Correspoding to 65536 } i := c.S2KCount switch { // Behave like GPG. Should we make 65536 the lowest value used? case i < 1024: i = 1024 case i > 65011712: i = 65011712 } return encodeCount(i) } // encodeCount converts an iterative "count" in the range 1024 to // 65011712, inclusive, to an encoded count. The return value is the // octet that is actually stored in the GPG file. encodeCount panics // if i is not in the above range (encodedCount above takes care to // pass i in the correct range). See RFC 4880 Section 3.7.7.1. func encodeCount(i int) uint8 { if i < 1024 || i > 65011712 { panic("count arg i outside the required range") } for encoded := 0; encoded < 256; encoded++ { count := decodeCount(uint8(encoded)) if count >= i { return uint8(encoded) } } return 255 } // decodeCount returns the s2k mode 3 iterative "count" corresponding to // the encoded octet c. func decodeCount(c uint8) int { return (16 + int(c&15)) << (uint32(c>>4) + 6) } // Simple writes to out the result of computing the Simple S2K function (RFC // 4880, section 3.7.1.1) using the given hash and input passphrase. func Simple(out []byte, h hash.Hash, in []byte) { Salted(out, h, in, nil) } var zero [1]byte // Salted writes to out the result of computing the Salted S2K function (RFC // 4880, section 3.7.1.2) using the given hash, input passphrase and salt. func Salted(out []byte, h hash.Hash, in []byte, salt []byte) { done := 0 var digest []byte for i := 0; done < len(out); i++ { h.Reset() for j := 0; j < i; j++ { h.Write(zero[:]) } h.Write(salt) h.Write(in) digest = h.Sum(digest[:0]) n := copy(out[done:], digest) done += n } } // Iterated writes to out the result of computing the Iterated and Salted S2K // function (RFC 4880, section 3.7.1.3) using the given hash, input passphrase, // salt and iteration count. func Iterated(out []byte, h hash.Hash, in []byte, salt []byte, count int) { combined := make([]byte, len(in)+len(salt)) copy(combined, salt) copy(combined[len(salt):], in) if count < len(combined) { count = len(combined) } done := 0 var digest []byte for i := 0; done < len(out); i++ { h.Reset() for j := 0; j < i; j++ { h.Write(zero[:]) } written := 0 for written < count { if written+len(combined) > count { todo := count - written h.Write(combined[:todo]) written = count } else { h.Write(combined) written += len(combined) } } digest = h.Sum(digest[:0]) n := copy(out[done:], digest) done += n } } // Parse reads a binary specification for a string-to-key transformation from r // and returns a function which performs that transform. func Parse(r io.Reader) (f func(out, in []byte), err error) { var buf [9]byte _, err = io.ReadFull(r, buf[:2]) if err != nil { return } hash, ok := HashIdToHash(buf[1]) if !ok { return nil, errors.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1]))) } if !hash.Available() { return nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hash))) } h := hash.New() switch buf[0] { case 0: f := func(out, in []byte) { Simple(out, h, in) } return f, nil case 1: _, err = io.ReadFull(r, buf[:8]) if err != nil { return } f := func(out, in []byte) { Salted(out, h, in, buf[:8]) } return f, nil case 3: _, err = io.ReadFull(r, buf[:9]) if err != nil { return } count := decodeCount(buf[8]) f := func(out, in []byte) { Iterated(out, h, in, buf[:8], count) } return f, nil } return nil, errors.UnsupportedError("S2K function") } // Serialize salts and stretches the given passphrase and writes the // resulting key into key. It also serializes an S2K descriptor to // w. The key stretching can be configured with c, which may be // nil. In that case, sensible defaults will be used. func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte, c *Config) error { var buf [11]byte buf[0] = 3 /* iterated and salted */ buf[1], _ = HashToHashId(c.hash()) salt := buf[2:10] if _, err := io.ReadFull(rand, salt); err != nil { return err } encodedCount := c.encodedCount() count := decodeCount(encodedCount) buf[10] = encodedCount if _, err := w.Write(buf[:]); err != nil { return err } Iterated(key, c.hash().New(), passphrase, salt, count) return nil } // hashToHashIdMapping contains pairs relating OpenPGP's hash identifier with // Go's crypto.Hash type. See RFC 4880, section 9.4. var hashToHashIdMapping = []struct { id byte hash crypto.Hash name string }{ {1, crypto.MD5, "MD5"}, {2, crypto.SHA1, "SHA1"}, {3, crypto.RIPEMD160, "RIPEMD160"}, {8, crypto.SHA256, "SHA256"}, {9, crypto.SHA384, "SHA384"}, {10, crypto.SHA512, "SHA512"}, {11, crypto.SHA224, "SHA224"}, } // HashIdToHash returns a crypto.Hash which corresponds to the given OpenPGP // hash id. func HashIdToHash(id byte) (h crypto.Hash, ok bool) { for _, m := range hashToHashIdMapping { if m.id == id { return m.hash, true } } return 0, false } // HashIdToString returns the name of the hash function corresponding to the // given OpenPGP hash id. func HashIdToString(id byte) (name string, ok bool) { for _, m := range hashToHashIdMapping { if m.id == id { return m.name, true } } return "", false } // HashToHashId returns an OpenPGP hash id which corresponds the given Hash. func HashToHashId(h crypto.Hash) (id byte, ok bool) { for _, m := range hashToHashIdMapping { if m.hash == h { return m.id, true } } return 0, false }
crypto/openpgp/s2k/s2k.go/0
{ "file_path": "crypto/openpgp/s2k/s2k.go", "repo_id": "crypto", "token_count": 2716 }
9
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package rc2 implements the RC2 cipher /* https://www.ietf.org/rfc/rfc2268.txt http://people.csail.mit.edu/rivest/pubs/KRRR98.pdf This code is licensed under the MIT license. */ package rc2 import ( "crypto/cipher" "encoding/binary" "math/bits" ) // The rc2 block size in bytes const BlockSize = 8 type rc2Cipher struct { k [64]uint16 } // New returns a new rc2 cipher with the given key and effective key length t1 func New(key []byte, t1 int) (cipher.Block, error) { // TODO(dgryski): error checking for key length return &rc2Cipher{ k: expandKey(key, t1), }, nil } func (*rc2Cipher) BlockSize() int { return BlockSize } var piTable = [256]byte{ 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad, } func expandKey(key []byte, t1 int) [64]uint16 { l := make([]byte, 128) copy(l, key) var t = len(key) var t8 = (t1 + 7) / 8 var tm = byte(255 % uint(1<<(8+uint(t1)-8*uint(t8)))) for i := len(key); i < 128; i++ { l[i] = piTable[l[i-1]+l[uint8(i-t)]] } l[128-t8] = piTable[l[128-t8]&tm] for i := 127 - t8; i >= 0; i-- { l[i] = piTable[l[i+1]^l[i+t8]] } var k [64]uint16 for i := range k { k[i] = uint16(l[2*i]) + uint16(l[2*i+1])*256 } return k } func (c *rc2Cipher) Encrypt(dst, src []byte) { r0 := binary.LittleEndian.Uint16(src[0:]) r1 := binary.LittleEndian.Uint16(src[2:]) r2 := binary.LittleEndian.Uint16(src[4:]) r3 := binary.LittleEndian.Uint16(src[6:]) var j int for j <= 16 { // mix r0 r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) r0 = bits.RotateLeft16(r0, 1) j++ // mix r1 r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) r1 = bits.RotateLeft16(r1, 2) j++ // mix r2 r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) r2 = bits.RotateLeft16(r2, 3) j++ // mix r3 r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) r3 = bits.RotateLeft16(r3, 5) j++ } r0 = r0 + c.k[r3&63] r1 = r1 + c.k[r0&63] r2 = r2 + c.k[r1&63] r3 = r3 + c.k[r2&63] for j <= 40 { // mix r0 r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) r0 = bits.RotateLeft16(r0, 1) j++ // mix r1 r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) r1 = bits.RotateLeft16(r1, 2) j++ // mix r2 r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) r2 = bits.RotateLeft16(r2, 3) j++ // mix r3 r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) r3 = bits.RotateLeft16(r3, 5) j++ } r0 = r0 + c.k[r3&63] r1 = r1 + c.k[r0&63] r2 = r2 + c.k[r1&63] r3 = r3 + c.k[r2&63] for j <= 60 { // mix r0 r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) r0 = bits.RotateLeft16(r0, 1) j++ // mix r1 r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) r1 = bits.RotateLeft16(r1, 2) j++ // mix r2 r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) r2 = bits.RotateLeft16(r2, 3) j++ // mix r3 r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) r3 = bits.RotateLeft16(r3, 5) j++ } binary.LittleEndian.PutUint16(dst[0:], r0) binary.LittleEndian.PutUint16(dst[2:], r1) binary.LittleEndian.PutUint16(dst[4:], r2) binary.LittleEndian.PutUint16(dst[6:], r3) } func (c *rc2Cipher) Decrypt(dst, src []byte) { r0 := binary.LittleEndian.Uint16(src[0:]) r1 := binary.LittleEndian.Uint16(src[2:]) r2 := binary.LittleEndian.Uint16(src[4:]) r3 := binary.LittleEndian.Uint16(src[6:]) j := 63 for j >= 44 { // unmix r3 r3 = bits.RotateLeft16(r3, 16-5) r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) j-- // unmix r2 r2 = bits.RotateLeft16(r2, 16-3) r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) j-- // unmix r1 r1 = bits.RotateLeft16(r1, 16-2) r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) j-- // unmix r0 r0 = bits.RotateLeft16(r0, 16-1) r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) j-- } r3 = r3 - c.k[r2&63] r2 = r2 - c.k[r1&63] r1 = r1 - c.k[r0&63] r0 = r0 - c.k[r3&63] for j >= 20 { // unmix r3 r3 = bits.RotateLeft16(r3, 16-5) r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) j-- // unmix r2 r2 = bits.RotateLeft16(r2, 16-3) r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) j-- // unmix r1 r1 = bits.RotateLeft16(r1, 16-2) r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) j-- // unmix r0 r0 = bits.RotateLeft16(r0, 16-1) r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) j-- } r3 = r3 - c.k[r2&63] r2 = r2 - c.k[r1&63] r1 = r1 - c.k[r0&63] r0 = r0 - c.k[r3&63] for j >= 0 { // unmix r3 r3 = bits.RotateLeft16(r3, 16-5) r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) j-- // unmix r2 r2 = bits.RotateLeft16(r2, 16-3) r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) j-- // unmix r1 r1 = bits.RotateLeft16(r1, 16-2) r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) j-- // unmix r0 r0 = bits.RotateLeft16(r0, 16-1) r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) j-- } binary.LittleEndian.PutUint16(dst[0:], r0) binary.LittleEndian.PutUint16(dst[2:], r1) binary.LittleEndian.PutUint16(dst[4:], r2) binary.LittleEndian.PutUint16(dst[6:], r3) }
crypto/pkcs12/internal/rc2/rc2.go/0
{ "file_path": "crypto/pkcs12/internal/rc2/rc2.go", "repo_id": "crypto", "token_count": 3945 }
10
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build amd64 && !purego && gc // This code was translated into a form compatible with 6a from the public // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // func salsa2020XORKeyStream(out, in *byte, n uint64, nonce, key *byte) // This needs up to 64 bytes at 360(R12); hence the non-obvious frame size. TEXT ·salsa2020XORKeyStream(SB),0,$456-40 // frame = 424 + 32 byte alignment MOVQ out+0(FP),DI MOVQ in+8(FP),SI MOVQ n+16(FP),DX MOVQ nonce+24(FP),CX MOVQ key+32(FP),R8 MOVQ SP,R12 ADDQ $31, R12 ANDQ $~31, R12 MOVQ DX,R9 MOVQ CX,DX MOVQ R8,R10 CMPQ R9,$0 JBE DONE START: MOVL 20(R10),CX MOVL 0(R10),R8 MOVL 0(DX),AX MOVL 16(R10),R11 MOVL CX,0(R12) MOVL R8, 4 (R12) MOVL AX, 8 (R12) MOVL R11, 12 (R12) MOVL 8(DX),CX MOVL 24(R10),R8 MOVL 4(R10),AX MOVL 4(DX),R11 MOVL CX,16(R12) MOVL R8, 20 (R12) MOVL AX, 24 (R12) MOVL R11, 28 (R12) MOVL 12(DX),CX MOVL 12(R10),DX MOVL 28(R10),R8 MOVL 8(R10),AX MOVL DX,32(R12) MOVL CX, 36 (R12) MOVL R8, 40 (R12) MOVL AX, 44 (R12) MOVQ $1634760805,DX MOVQ $857760878,CX MOVQ $2036477234,R8 MOVQ $1797285236,AX MOVL DX,48(R12) MOVL CX, 52 (R12) MOVL R8, 56 (R12) MOVL AX, 60 (R12) CMPQ R9,$256 JB BYTESBETWEEN1AND255 MOVOA 48(R12),X0 PSHUFL $0X55,X0,X1 PSHUFL $0XAA,X0,X2 PSHUFL $0XFF,X0,X3 PSHUFL $0X00,X0,X0 MOVOA X1,64(R12) MOVOA X2,80(R12) MOVOA X3,96(R12) MOVOA X0,112(R12) MOVOA 0(R12),X0 PSHUFL $0XAA,X0,X1 PSHUFL $0XFF,X0,X2 PSHUFL $0X00,X0,X3 PSHUFL $0X55,X0,X0 MOVOA X1,128(R12) MOVOA X2,144(R12) MOVOA X3,160(R12) MOVOA X0,176(R12) MOVOA 16(R12),X0 PSHUFL $0XFF,X0,X1 PSHUFL $0X55,X0,X2 PSHUFL $0XAA,X0,X0 MOVOA X1,192(R12) MOVOA X2,208(R12) MOVOA X0,224(R12) MOVOA 32(R12),X0 PSHUFL $0X00,X0,X1 PSHUFL $0XAA,X0,X2 PSHUFL $0XFF,X0,X0 MOVOA X1,240(R12) MOVOA X2,256(R12) MOVOA X0,272(R12) BYTESATLEAST256: MOVL 16(R12),DX MOVL 36 (R12),CX MOVL DX,288(R12) MOVL CX,304(R12) SHLQ $32,CX ADDQ CX,DX ADDQ $1,DX MOVQ DX,CX SHRQ $32,CX MOVL DX, 292 (R12) MOVL CX, 308 (R12) ADDQ $1,DX MOVQ DX,CX SHRQ $32,CX MOVL DX, 296 (R12) MOVL CX, 312 (R12) ADDQ $1,DX MOVQ DX,CX SHRQ $32,CX MOVL DX, 300 (R12) MOVL CX, 316 (R12) ADDQ $1,DX MOVQ DX,CX SHRQ $32,CX MOVL DX,16(R12) MOVL CX, 36 (R12) MOVQ R9,352(R12) MOVQ $20,DX MOVOA 64(R12),X0 MOVOA 80(R12),X1 MOVOA 96(R12),X2 MOVOA 256(R12),X3 MOVOA 272(R12),X4 MOVOA 128(R12),X5 MOVOA 144(R12),X6 MOVOA 176(R12),X7 MOVOA 192(R12),X8 MOVOA 208(R12),X9 MOVOA 224(R12),X10 MOVOA 304(R12),X11 MOVOA 112(R12),X12 MOVOA 160(R12),X13 MOVOA 240(R12),X14 MOVOA 288(R12),X15 MAINLOOP1: MOVOA X1,320(R12) MOVOA X2,336(R12) MOVOA X13,X1 PADDL X12,X1 MOVOA X1,X2 PSLLL $7,X1 PXOR X1,X14 PSRLL $25,X2 PXOR X2,X14 MOVOA X7,X1 PADDL X0,X1 MOVOA X1,X2 PSLLL $7,X1 PXOR X1,X11 PSRLL $25,X2 PXOR X2,X11 MOVOA X12,X1 PADDL X14,X1 MOVOA X1,X2 PSLLL $9,X1 PXOR X1,X15 PSRLL $23,X2 PXOR X2,X15 MOVOA X0,X1 PADDL X11,X1 MOVOA X1,X2 PSLLL $9,X1 PXOR X1,X9 PSRLL $23,X2 PXOR X2,X9 MOVOA X14,X1 PADDL X15,X1 MOVOA X1,X2 PSLLL $13,X1 PXOR X1,X13 PSRLL $19,X2 PXOR X2,X13 MOVOA X11,X1 PADDL X9,X1 MOVOA X1,X2 PSLLL $13,X1 PXOR X1,X7 PSRLL $19,X2 PXOR X2,X7 MOVOA X15,X1 PADDL X13,X1 MOVOA X1,X2 PSLLL $18,X1 PXOR X1,X12 PSRLL $14,X2 PXOR X2,X12 MOVOA 320(R12),X1 MOVOA X12,320(R12) MOVOA X9,X2 PADDL X7,X2 MOVOA X2,X12 PSLLL $18,X2 PXOR X2,X0 PSRLL $14,X12 PXOR X12,X0 MOVOA X5,X2 PADDL X1,X2 MOVOA X2,X12 PSLLL $7,X2 PXOR X2,X3 PSRLL $25,X12 PXOR X12,X3 MOVOA 336(R12),X2 MOVOA X0,336(R12) MOVOA X6,X0 PADDL X2,X0 MOVOA X0,X12 PSLLL $7,X0 PXOR X0,X4 PSRLL $25,X12 PXOR X12,X4 MOVOA X1,X0 PADDL X3,X0 MOVOA X0,X12 PSLLL $9,X0 PXOR X0,X10 PSRLL $23,X12 PXOR X12,X10 MOVOA X2,X0 PADDL X4,X0 MOVOA X0,X12 PSLLL $9,X0 PXOR X0,X8 PSRLL $23,X12 PXOR X12,X8 MOVOA X3,X0 PADDL X10,X0 MOVOA X0,X12 PSLLL $13,X0 PXOR X0,X5 PSRLL $19,X12 PXOR X12,X5 MOVOA X4,X0 PADDL X8,X0 MOVOA X0,X12 PSLLL $13,X0 PXOR X0,X6 PSRLL $19,X12 PXOR X12,X6 MOVOA X10,X0 PADDL X5,X0 MOVOA X0,X12 PSLLL $18,X0 PXOR X0,X1 PSRLL $14,X12 PXOR X12,X1 MOVOA 320(R12),X0 MOVOA X1,320(R12) MOVOA X4,X1 PADDL X0,X1 MOVOA X1,X12 PSLLL $7,X1 PXOR X1,X7 PSRLL $25,X12 PXOR X12,X7 MOVOA X8,X1 PADDL X6,X1 MOVOA X1,X12 PSLLL $18,X1 PXOR X1,X2 PSRLL $14,X12 PXOR X12,X2 MOVOA 336(R12),X12 MOVOA X2,336(R12) MOVOA X14,X1 PADDL X12,X1 MOVOA X1,X2 PSLLL $7,X1 PXOR X1,X5 PSRLL $25,X2 PXOR X2,X5 MOVOA X0,X1 PADDL X7,X1 MOVOA X1,X2 PSLLL $9,X1 PXOR X1,X10 PSRLL $23,X2 PXOR X2,X10 MOVOA X12,X1 PADDL X5,X1 MOVOA X1,X2 PSLLL $9,X1 PXOR X1,X8 PSRLL $23,X2 PXOR X2,X8 MOVOA X7,X1 PADDL X10,X1 MOVOA X1,X2 PSLLL $13,X1 PXOR X1,X4 PSRLL $19,X2 PXOR X2,X4 MOVOA X5,X1 PADDL X8,X1 MOVOA X1,X2 PSLLL $13,X1 PXOR X1,X14 PSRLL $19,X2 PXOR X2,X14 MOVOA X10,X1 PADDL X4,X1 MOVOA X1,X2 PSLLL $18,X1 PXOR X1,X0 PSRLL $14,X2 PXOR X2,X0 MOVOA 320(R12),X1 MOVOA X0,320(R12) MOVOA X8,X0 PADDL X14,X0 MOVOA X0,X2 PSLLL $18,X0 PXOR X0,X12 PSRLL $14,X2 PXOR X2,X12 MOVOA X11,X0 PADDL X1,X0 MOVOA X0,X2 PSLLL $7,X0 PXOR X0,X6 PSRLL $25,X2 PXOR X2,X6 MOVOA 336(R12),X2 MOVOA X12,336(R12) MOVOA X3,X0 PADDL X2,X0 MOVOA X0,X12 PSLLL $7,X0 PXOR X0,X13 PSRLL $25,X12 PXOR X12,X13 MOVOA X1,X0 PADDL X6,X0 MOVOA X0,X12 PSLLL $9,X0 PXOR X0,X15 PSRLL $23,X12 PXOR X12,X15 MOVOA X2,X0 PADDL X13,X0 MOVOA X0,X12 PSLLL $9,X0 PXOR X0,X9 PSRLL $23,X12 PXOR X12,X9 MOVOA X6,X0 PADDL X15,X0 MOVOA X0,X12 PSLLL $13,X0 PXOR X0,X11 PSRLL $19,X12 PXOR X12,X11 MOVOA X13,X0 PADDL X9,X0 MOVOA X0,X12 PSLLL $13,X0 PXOR X0,X3 PSRLL $19,X12 PXOR X12,X3 MOVOA X15,X0 PADDL X11,X0 MOVOA X0,X12 PSLLL $18,X0 PXOR X0,X1 PSRLL $14,X12 PXOR X12,X1 MOVOA X9,X0 PADDL X3,X0 MOVOA X0,X12 PSLLL $18,X0 PXOR X0,X2 PSRLL $14,X12 PXOR X12,X2 MOVOA 320(R12),X12 MOVOA 336(R12),X0 SUBQ $2,DX JA MAINLOOP1 PADDL 112(R12),X12 PADDL 176(R12),X7 PADDL 224(R12),X10 PADDL 272(R12),X4 MOVD X12,DX MOVD X7,CX MOVD X10,R8 MOVD X4,R9 PSHUFL $0X39,X12,X12 PSHUFL $0X39,X7,X7 PSHUFL $0X39,X10,X10 PSHUFL $0X39,X4,X4 XORL 0(SI),DX XORL 4(SI),CX XORL 8(SI),R8 XORL 12(SI),R9 MOVL DX,0(DI) MOVL CX,4(DI) MOVL R8,8(DI) MOVL R9,12(DI) MOVD X12,DX MOVD X7,CX MOVD X10,R8 MOVD X4,R9 PSHUFL $0X39,X12,X12 PSHUFL $0X39,X7,X7 PSHUFL $0X39,X10,X10 PSHUFL $0X39,X4,X4 XORL 64(SI),DX XORL 68(SI),CX XORL 72(SI),R8 XORL 76(SI),R9 MOVL DX,64(DI) MOVL CX,68(DI) MOVL R8,72(DI) MOVL R9,76(DI) MOVD X12,DX MOVD X7,CX MOVD X10,R8 MOVD X4,R9 PSHUFL $0X39,X12,X12 PSHUFL $0X39,X7,X7 PSHUFL $0X39,X10,X10 PSHUFL $0X39,X4,X4 XORL 128(SI),DX XORL 132(SI),CX XORL 136(SI),R8 XORL 140(SI),R9 MOVL DX,128(DI) MOVL CX,132(DI) MOVL R8,136(DI) MOVL R9,140(DI) MOVD X12,DX MOVD X7,CX MOVD X10,R8 MOVD X4,R9 XORL 192(SI),DX XORL 196(SI),CX XORL 200(SI),R8 XORL 204(SI),R9 MOVL DX,192(DI) MOVL CX,196(DI) MOVL R8,200(DI) MOVL R9,204(DI) PADDL 240(R12),X14 PADDL 64(R12),X0 PADDL 128(R12),X5 PADDL 192(R12),X8 MOVD X14,DX MOVD X0,CX MOVD X5,R8 MOVD X8,R9 PSHUFL $0X39,X14,X14 PSHUFL $0X39,X0,X0 PSHUFL $0X39,X5,X5 PSHUFL $0X39,X8,X8 XORL 16(SI),DX XORL 20(SI),CX XORL 24(SI),R8 XORL 28(SI),R9 MOVL DX,16(DI) MOVL CX,20(DI) MOVL R8,24(DI) MOVL R9,28(DI) MOVD X14,DX MOVD X0,CX MOVD X5,R8 MOVD X8,R9 PSHUFL $0X39,X14,X14 PSHUFL $0X39,X0,X0 PSHUFL $0X39,X5,X5 PSHUFL $0X39,X8,X8 XORL 80(SI),DX XORL 84(SI),CX XORL 88(SI),R8 XORL 92(SI),R9 MOVL DX,80(DI) MOVL CX,84(DI) MOVL R8,88(DI) MOVL R9,92(DI) MOVD X14,DX MOVD X0,CX MOVD X5,R8 MOVD X8,R9 PSHUFL $0X39,X14,X14 PSHUFL $0X39,X0,X0 PSHUFL $0X39,X5,X5 PSHUFL $0X39,X8,X8 XORL 144(SI),DX XORL 148(SI),CX XORL 152(SI),R8 XORL 156(SI),R9 MOVL DX,144(DI) MOVL CX,148(DI) MOVL R8,152(DI) MOVL R9,156(DI) MOVD X14,DX MOVD X0,CX MOVD X5,R8 MOVD X8,R9 XORL 208(SI),DX XORL 212(SI),CX XORL 216(SI),R8 XORL 220(SI),R9 MOVL DX,208(DI) MOVL CX,212(DI) MOVL R8,216(DI) MOVL R9,220(DI) PADDL 288(R12),X15 PADDL 304(R12),X11 PADDL 80(R12),X1 PADDL 144(R12),X6 MOVD X15,DX MOVD X11,CX MOVD X1,R8 MOVD X6,R9 PSHUFL $0X39,X15,X15 PSHUFL $0X39,X11,X11 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X6,X6 XORL 32(SI),DX XORL 36(SI),CX XORL 40(SI),R8 XORL 44(SI),R9 MOVL DX,32(DI) MOVL CX,36(DI) MOVL R8,40(DI) MOVL R9,44(DI) MOVD X15,DX MOVD X11,CX MOVD X1,R8 MOVD X6,R9 PSHUFL $0X39,X15,X15 PSHUFL $0X39,X11,X11 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X6,X6 XORL 96(SI),DX XORL 100(SI),CX XORL 104(SI),R8 XORL 108(SI),R9 MOVL DX,96(DI) MOVL CX,100(DI) MOVL R8,104(DI) MOVL R9,108(DI) MOVD X15,DX MOVD X11,CX MOVD X1,R8 MOVD X6,R9 PSHUFL $0X39,X15,X15 PSHUFL $0X39,X11,X11 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X6,X6 XORL 160(SI),DX XORL 164(SI),CX XORL 168(SI),R8 XORL 172(SI),R9 MOVL DX,160(DI) MOVL CX,164(DI) MOVL R8,168(DI) MOVL R9,172(DI) MOVD X15,DX MOVD X11,CX MOVD X1,R8 MOVD X6,R9 XORL 224(SI),DX XORL 228(SI),CX XORL 232(SI),R8 XORL 236(SI),R9 MOVL DX,224(DI) MOVL CX,228(DI) MOVL R8,232(DI) MOVL R9,236(DI) PADDL 160(R12),X13 PADDL 208(R12),X9 PADDL 256(R12),X3 PADDL 96(R12),X2 MOVD X13,DX MOVD X9,CX MOVD X3,R8 MOVD X2,R9 PSHUFL $0X39,X13,X13 PSHUFL $0X39,X9,X9 PSHUFL $0X39,X3,X3 PSHUFL $0X39,X2,X2 XORL 48(SI),DX XORL 52(SI),CX XORL 56(SI),R8 XORL 60(SI),R9 MOVL DX,48(DI) MOVL CX,52(DI) MOVL R8,56(DI) MOVL R9,60(DI) MOVD X13,DX MOVD X9,CX MOVD X3,R8 MOVD X2,R9 PSHUFL $0X39,X13,X13 PSHUFL $0X39,X9,X9 PSHUFL $0X39,X3,X3 PSHUFL $0X39,X2,X2 XORL 112(SI),DX XORL 116(SI),CX XORL 120(SI),R8 XORL 124(SI),R9 MOVL DX,112(DI) MOVL CX,116(DI) MOVL R8,120(DI) MOVL R9,124(DI) MOVD X13,DX MOVD X9,CX MOVD X3,R8 MOVD X2,R9 PSHUFL $0X39,X13,X13 PSHUFL $0X39,X9,X9 PSHUFL $0X39,X3,X3 PSHUFL $0X39,X2,X2 XORL 176(SI),DX XORL 180(SI),CX XORL 184(SI),R8 XORL 188(SI),R9 MOVL DX,176(DI) MOVL CX,180(DI) MOVL R8,184(DI) MOVL R9,188(DI) MOVD X13,DX MOVD X9,CX MOVD X3,R8 MOVD X2,R9 XORL 240(SI),DX XORL 244(SI),CX XORL 248(SI),R8 XORL 252(SI),R9 MOVL DX,240(DI) MOVL CX,244(DI) MOVL R8,248(DI) MOVL R9,252(DI) MOVQ 352(R12),R9 SUBQ $256,R9 ADDQ $256,SI ADDQ $256,DI CMPQ R9,$256 JAE BYTESATLEAST256 CMPQ R9,$0 JBE DONE BYTESBETWEEN1AND255: CMPQ R9,$64 JAE NOCOPY MOVQ DI,DX LEAQ 360(R12),DI MOVQ R9,CX REP; MOVSB LEAQ 360(R12),DI LEAQ 360(R12),SI NOCOPY: MOVQ R9,352(R12) MOVOA 48(R12),X0 MOVOA 0(R12),X1 MOVOA 16(R12),X2 MOVOA 32(R12),X3 MOVOA X1,X4 MOVQ $20,CX MAINLOOP2: PADDL X0,X4 MOVOA X0,X5 MOVOA X4,X6 PSLLL $7,X4 PSRLL $25,X6 PXOR X4,X3 PXOR X6,X3 PADDL X3,X5 MOVOA X3,X4 MOVOA X5,X6 PSLLL $9,X5 PSRLL $23,X6 PXOR X5,X2 PSHUFL $0X93,X3,X3 PXOR X6,X2 PADDL X2,X4 MOVOA X2,X5 MOVOA X4,X6 PSLLL $13,X4 PSRLL $19,X6 PXOR X4,X1 PSHUFL $0X4E,X2,X2 PXOR X6,X1 PADDL X1,X5 MOVOA X3,X4 MOVOA X5,X6 PSLLL $18,X5 PSRLL $14,X6 PXOR X5,X0 PSHUFL $0X39,X1,X1 PXOR X6,X0 PADDL X0,X4 MOVOA X0,X5 MOVOA X4,X6 PSLLL $7,X4 PSRLL $25,X6 PXOR X4,X1 PXOR X6,X1 PADDL X1,X5 MOVOA X1,X4 MOVOA X5,X6 PSLLL $9,X5 PSRLL $23,X6 PXOR X5,X2 PSHUFL $0X93,X1,X1 PXOR X6,X2 PADDL X2,X4 MOVOA X2,X5 MOVOA X4,X6 PSLLL $13,X4 PSRLL $19,X6 PXOR X4,X3 PSHUFL $0X4E,X2,X2 PXOR X6,X3 PADDL X3,X5 MOVOA X1,X4 MOVOA X5,X6 PSLLL $18,X5 PSRLL $14,X6 PXOR X5,X0 PSHUFL $0X39,X3,X3 PXOR X6,X0 PADDL X0,X4 MOVOA X0,X5 MOVOA X4,X6 PSLLL $7,X4 PSRLL $25,X6 PXOR X4,X3 PXOR X6,X3 PADDL X3,X5 MOVOA X3,X4 MOVOA X5,X6 PSLLL $9,X5 PSRLL $23,X6 PXOR X5,X2 PSHUFL $0X93,X3,X3 PXOR X6,X2 PADDL X2,X4 MOVOA X2,X5 MOVOA X4,X6 PSLLL $13,X4 PSRLL $19,X6 PXOR X4,X1 PSHUFL $0X4E,X2,X2 PXOR X6,X1 PADDL X1,X5 MOVOA X3,X4 MOVOA X5,X6 PSLLL $18,X5 PSRLL $14,X6 PXOR X5,X0 PSHUFL $0X39,X1,X1 PXOR X6,X0 PADDL X0,X4 MOVOA X0,X5 MOVOA X4,X6 PSLLL $7,X4 PSRLL $25,X6 PXOR X4,X1 PXOR X6,X1 PADDL X1,X5 MOVOA X1,X4 MOVOA X5,X6 PSLLL $9,X5 PSRLL $23,X6 PXOR X5,X2 PSHUFL $0X93,X1,X1 PXOR X6,X2 PADDL X2,X4 MOVOA X2,X5 MOVOA X4,X6 PSLLL $13,X4 PSRLL $19,X6 PXOR X4,X3 PSHUFL $0X4E,X2,X2 PXOR X6,X3 SUBQ $4,CX PADDL X3,X5 MOVOA X1,X4 MOVOA X5,X6 PSLLL $18,X5 PXOR X7,X7 PSRLL $14,X6 PXOR X5,X0 PSHUFL $0X39,X3,X3 PXOR X6,X0 JA MAINLOOP2 PADDL 48(R12),X0 PADDL 0(R12),X1 PADDL 16(R12),X2 PADDL 32(R12),X3 MOVD X0,CX MOVD X1,R8 MOVD X2,R9 MOVD X3,AX PSHUFL $0X39,X0,X0 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X2,X2 PSHUFL $0X39,X3,X3 XORL 0(SI),CX XORL 48(SI),R8 XORL 32(SI),R9 XORL 16(SI),AX MOVL CX,0(DI) MOVL R8,48(DI) MOVL R9,32(DI) MOVL AX,16(DI) MOVD X0,CX MOVD X1,R8 MOVD X2,R9 MOVD X3,AX PSHUFL $0X39,X0,X0 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X2,X2 PSHUFL $0X39,X3,X3 XORL 20(SI),CX XORL 4(SI),R8 XORL 52(SI),R9 XORL 36(SI),AX MOVL CX,20(DI) MOVL R8,4(DI) MOVL R9,52(DI) MOVL AX,36(DI) MOVD X0,CX MOVD X1,R8 MOVD X2,R9 MOVD X3,AX PSHUFL $0X39,X0,X0 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X2,X2 PSHUFL $0X39,X3,X3 XORL 40(SI),CX XORL 24(SI),R8 XORL 8(SI),R9 XORL 56(SI),AX MOVL CX,40(DI) MOVL R8,24(DI) MOVL R9,8(DI) MOVL AX,56(DI) MOVD X0,CX MOVD X1,R8 MOVD X2,R9 MOVD X3,AX XORL 60(SI),CX XORL 44(SI),R8 XORL 28(SI),R9 XORL 12(SI),AX MOVL CX,60(DI) MOVL R8,44(DI) MOVL R9,28(DI) MOVL AX,12(DI) MOVQ 352(R12),R9 MOVL 16(R12),CX MOVL 36 (R12),R8 ADDQ $1,CX SHLQ $32,R8 ADDQ R8,CX MOVQ CX,R8 SHRQ $32,R8 MOVL CX,16(R12) MOVL R8, 36 (R12) CMPQ R9,$64 JA BYTESATLEAST65 JAE BYTESATLEAST64 MOVQ DI,SI MOVQ DX,DI MOVQ R9,CX REP; MOVSB BYTESATLEAST64: DONE: RET BYTESATLEAST65: SUBQ $64,R9 ADDQ $64,DI ADDQ $64,SI JMP BYTESBETWEEN1AND255
crypto/salsa20/salsa/salsa20_amd64.s/0
{ "file_path": "crypto/salsa20/salsa/salsa20_amd64.s", "repo_id": "crypto", "token_count": 9767 }
11
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package agent import ( "bytes" "crypto/rand" "crypto/subtle" "errors" "fmt" "sync" "time" "golang.org/x/crypto/ssh" ) type privKey struct { signer ssh.Signer comment string expire *time.Time } type keyring struct { mu sync.Mutex keys []privKey locked bool passphrase []byte } var errLocked = errors.New("agent: locked") // NewKeyring returns an Agent that holds keys in memory. It is safe // for concurrent use by multiple goroutines. func NewKeyring() Agent { return &keyring{} } // RemoveAll removes all identities. func (r *keyring) RemoveAll() error { r.mu.Lock() defer r.mu.Unlock() if r.locked { return errLocked } r.keys = nil return nil } // removeLocked does the actual key removal. The caller must already be holding the // keyring mutex. func (r *keyring) removeLocked(want []byte) error { found := false for i := 0; i < len(r.keys); { if bytes.Equal(r.keys[i].signer.PublicKey().Marshal(), want) { found = true r.keys[i] = r.keys[len(r.keys)-1] r.keys = r.keys[:len(r.keys)-1] continue } else { i++ } } if !found { return errors.New("agent: key not found") } return nil } // Remove removes all identities with the given public key. func (r *keyring) Remove(key ssh.PublicKey) error { r.mu.Lock() defer r.mu.Unlock() if r.locked { return errLocked } return r.removeLocked(key.Marshal()) } // Lock locks the agent. Sign and Remove will fail, and List will return an empty list. func (r *keyring) Lock(passphrase []byte) error { r.mu.Lock() defer r.mu.Unlock() if r.locked { return errLocked } r.locked = true r.passphrase = passphrase return nil } // Unlock undoes the effect of Lock func (r *keyring) Unlock(passphrase []byte) error { r.mu.Lock() defer r.mu.Unlock() if !r.locked { return errors.New("agent: not locked") } if 1 != subtle.ConstantTimeCompare(passphrase, r.passphrase) { return fmt.Errorf("agent: incorrect passphrase") } r.locked = false r.passphrase = nil return nil } // expireKeysLocked removes expired keys from the keyring. If a key was added // with a lifetimesecs contraint and seconds >= lifetimesecs seconds have // elapsed, it is removed. The caller *must* be holding the keyring mutex. func (r *keyring) expireKeysLocked() { for _, k := range r.keys { if k.expire != nil && time.Now().After(*k.expire) { r.removeLocked(k.signer.PublicKey().Marshal()) } } } // List returns the identities known to the agent. func (r *keyring) List() ([]*Key, error) { r.mu.Lock() defer r.mu.Unlock() if r.locked { // section 2.7: locked agents return empty. return nil, nil } r.expireKeysLocked() var ids []*Key for _, k := range r.keys { pub := k.signer.PublicKey() ids = append(ids, &Key{ Format: pub.Type(), Blob: pub.Marshal(), Comment: k.comment}) } return ids, nil } // Insert adds a private key to the keyring. If a certificate // is given, that certificate is added as public key. Note that // any constraints given are ignored. func (r *keyring) Add(key AddedKey) error { r.mu.Lock() defer r.mu.Unlock() if r.locked { return errLocked } signer, err := ssh.NewSignerFromKey(key.PrivateKey) if err != nil { return err } if cert := key.Certificate; cert != nil { signer, err = ssh.NewCertSigner(cert, signer) if err != nil { return err } } p := privKey{ signer: signer, comment: key.Comment, } if key.LifetimeSecs > 0 { t := time.Now().Add(time.Duration(key.LifetimeSecs) * time.Second) p.expire = &t } r.keys = append(r.keys, p) return nil } // Sign returns a signature for the data. func (r *keyring) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) { return r.SignWithFlags(key, data, 0) } func (r *keyring) SignWithFlags(key ssh.PublicKey, data []byte, flags SignatureFlags) (*ssh.Signature, error) { r.mu.Lock() defer r.mu.Unlock() if r.locked { return nil, errLocked } r.expireKeysLocked() wanted := key.Marshal() for _, k := range r.keys { if bytes.Equal(k.signer.PublicKey().Marshal(), wanted) { if flags == 0 { return k.signer.Sign(rand.Reader, data) } else { if algorithmSigner, ok := k.signer.(ssh.AlgorithmSigner); !ok { return nil, fmt.Errorf("agent: signature does not support non-default signature algorithm: %T", k.signer) } else { var algorithm string switch flags { case SignatureFlagRsaSha256: algorithm = ssh.KeyAlgoRSASHA256 case SignatureFlagRsaSha512: algorithm = ssh.KeyAlgoRSASHA512 default: return nil, fmt.Errorf("agent: unsupported signature flags: %d", flags) } return algorithmSigner.SignWithAlgorithm(rand.Reader, data, algorithm) } } } } return nil, errors.New("not found") } // Signers returns signers for all the known keys. func (r *keyring) Signers() ([]ssh.Signer, error) { r.mu.Lock() defer r.mu.Unlock() if r.locked { return nil, errLocked } r.expireKeysLocked() s := make([]ssh.Signer, 0, len(r.keys)) for _, k := range r.keys { s = append(s, k.signer) } return s, nil } // The keyring does not support any extensions func (r *keyring) Extension(extensionType string, contents []byte) ([]byte, error) { return nil, ErrExtensionUnsupported }
crypto/ssh/agent/keyring.go/0
{ "file_path": "crypto/ssh/agent/keyring.go", "repo_id": "crypto", "token_count": 2086 }
12
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "crypto/rand" "errors" "fmt" "net" "strings" "testing" ) func TestClientVersion(t *testing.T) { for _, tt := range []struct { name string version string multiLine string wantErr bool }{ { name: "default version", version: packageVersion, }, { name: "custom version", version: "SSH-2.0-CustomClientVersionString", }, { name: "good multi line version", version: packageVersion, multiLine: strings.Repeat("ignored\r\n", 20), }, { name: "bad multi line version", version: packageVersion, multiLine: "bad multi line version", wantErr: true, }, { name: "long multi line version", version: packageVersion, multiLine: strings.Repeat("long multi line version\r\n", 50)[:256], wantErr: true, }, } { t.Run(tt.name, func(t *testing.T) { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() go func() { if tt.multiLine != "" { c1.Write([]byte(tt.multiLine)) } NewClientConn(c1, "", &ClientConfig{ ClientVersion: tt.version, HostKeyCallback: InsecureIgnoreHostKey(), }) c1.Close() }() conf := &ServerConfig{NoClientAuth: true} conf.AddHostKey(testSigners["rsa"]) conn, _, _, err := NewServerConn(c2, conf) if err == nil == tt.wantErr { t.Fatalf("got err %v; wantErr %t", err, tt.wantErr) } if tt.wantErr { // Don't verify the version on an expected error. return } if got := string(conn.ClientVersion()); got != tt.version { t.Fatalf("got %q; want %q", got, tt.version) } }) } } func TestHostKeyCheck(t *testing.T) { for _, tt := range []struct { name string wantError string key PublicKey }{ {"no callback", "must specify HostKeyCallback", nil}, {"correct key", "", testSigners["rsa"].PublicKey()}, {"mismatch", "mismatch", testSigners["ecdsa"].PublicKey()}, } { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() serverConf := &ServerConfig{ NoClientAuth: true, } serverConf.AddHostKey(testSigners["rsa"]) go NewServerConn(c1, serverConf) clientConf := ClientConfig{ User: "user", } if tt.key != nil { clientConf.HostKeyCallback = FixedHostKey(tt.key) } _, _, _, err = NewClientConn(c2, "", &clientConf) if err != nil { if tt.wantError == "" || !strings.Contains(err.Error(), tt.wantError) { t.Errorf("%s: got error %q, missing %q", tt.name, err.Error(), tt.wantError) } } else if tt.wantError != "" { t.Errorf("%s: succeeded, but want error string %q", tt.name, tt.wantError) } } } func TestVerifyHostKeySignature(t *testing.T) { for _, tt := range []struct { key string signAlgo string verifyAlgo string wantError string }{ {"rsa", KeyAlgoRSA, KeyAlgoRSA, ""}, {"rsa", KeyAlgoRSASHA256, KeyAlgoRSASHA256, ""}, {"rsa", KeyAlgoRSA, KeyAlgoRSASHA512, `ssh: invalid signature algorithm "ssh-rsa", expected "rsa-sha2-512"`}, {"ed25519", KeyAlgoED25519, KeyAlgoED25519, ""}, } { key := testSigners[tt.key].PublicKey() s, ok := testSigners[tt.key].(AlgorithmSigner) if !ok { t.Fatalf("needed an AlgorithmSigner") } sig, err := s.SignWithAlgorithm(rand.Reader, []byte("test"), tt.signAlgo) if err != nil { t.Fatalf("couldn't sign: %q", err) } b := bytes.Buffer{} writeString(&b, []byte(sig.Format)) writeString(&b, sig.Blob) result := kexResult{Signature: b.Bytes(), H: []byte("test")} err = verifyHostKeySignature(key, tt.verifyAlgo, &result) if err != nil { if tt.wantError == "" || !strings.Contains(err.Error(), tt.wantError) { t.Errorf("got error %q, expecting %q", err.Error(), tt.wantError) } } else if tt.wantError != "" { t.Errorf("succeeded, but want error string %q", tt.wantError) } } } func TestBannerCallback(t *testing.T) { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() serverConf := &ServerConfig{ PasswordCallback: func(conn ConnMetadata, password []byte) (*Permissions, error) { return &Permissions{}, nil }, BannerCallback: func(conn ConnMetadata) string { return "Hello World" }, } serverConf.AddHostKey(testSigners["rsa"]) go NewServerConn(c1, serverConf) var receivedBanner string var bannerCount int clientConf := ClientConfig{ Auth: []AuthMethod{ Password("123"), }, User: "user", HostKeyCallback: InsecureIgnoreHostKey(), BannerCallback: func(message string) error { bannerCount++ receivedBanner = message return nil }, } _, _, _, err = NewClientConn(c2, "", &clientConf) if err != nil { t.Fatal(err) } if bannerCount != 1 { t.Errorf("got %d banners; want 1", bannerCount) } expected := "Hello World" if receivedBanner != expected { t.Fatalf("got %s; want %s", receivedBanner, expected) } } func TestNewClientConn(t *testing.T) { errHostKeyMismatch := errors.New("host key mismatch") for _, tt := range []struct { name string user string simulateHostKeyMismatch HostKeyCallback }{ { name: "good user field for ConnMetadata", user: "testuser", }, { name: "empty user field for ConnMetadata", user: "", }, { name: "host key mismatch", user: "testuser", simulateHostKeyMismatch: func(hostname string, remote net.Addr, key PublicKey) error { return fmt.Errorf("%w: %s", errHostKeyMismatch, bytes.TrimSpace(MarshalAuthorizedKey(key))) }, }, } { t.Run(tt.name, func(t *testing.T) { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() serverConf := &ServerConfig{ PasswordCallback: func(conn ConnMetadata, password []byte) (*Permissions, error) { return &Permissions{}, nil }, } serverConf.AddHostKey(testSigners["rsa"]) go NewServerConn(c1, serverConf) clientConf := &ClientConfig{ User: tt.user, Auth: []AuthMethod{ Password("testpw"), }, HostKeyCallback: InsecureIgnoreHostKey(), } if tt.simulateHostKeyMismatch != nil { clientConf.HostKeyCallback = tt.simulateHostKeyMismatch } clientConn, _, _, err := NewClientConn(c2, "", clientConf) if err != nil { if tt.simulateHostKeyMismatch != nil && errors.Is(err, errHostKeyMismatch) { return } t.Fatal(err) } if userGot := clientConn.User(); userGot != tt.user { t.Errorf("got user %q; want user %q", userGot, tt.user) } }) } } func TestUnsupportedAlgorithm(t *testing.T) { for _, tt := range []struct { name string config Config wantError string }{ { "unsupported KEX", Config{ KeyExchanges: []string{"unsupported"}, }, "no common algorithm", }, { "unsupported and supported KEXs", Config{ KeyExchanges: []string{"unsupported", kexAlgoCurve25519SHA256}, }, "", }, { "unsupported cipher", Config{ Ciphers: []string{"unsupported"}, }, "no common algorithm", }, { "unsupported and supported ciphers", Config{ Ciphers: []string{"unsupported", chacha20Poly1305ID}, }, "", }, { "unsupported MAC", Config{ MACs: []string{"unsupported"}, // MAC is used for non AAED ciphers. Ciphers: []string{"aes256-ctr"}, }, "no common algorithm", }, { "unsupported and supported MACs", Config{ MACs: []string{"unsupported", "hmac-sha2-256-etm@openssh.com"}, // MAC is used for non AAED ciphers. Ciphers: []string{"aes256-ctr"}, }, "", }, } { t.Run(tt.name, func(t *testing.T) { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() serverConf := &ServerConfig{ Config: tt.config, PasswordCallback: func(conn ConnMetadata, password []byte) (*Permissions, error) { return &Permissions{}, nil }, } serverConf.AddHostKey(testSigners["rsa"]) go NewServerConn(c1, serverConf) clientConf := &ClientConfig{ User: "testuser", Config: tt.config, Auth: []AuthMethod{ Password("testpw"), }, HostKeyCallback: InsecureIgnoreHostKey(), } _, _, _, err = NewClientConn(c2, "", clientConf) if err != nil { if tt.wantError == "" || !strings.Contains(err.Error(), tt.wantError) { t.Errorf("%s: got error %q, missing %q", tt.name, err.Error(), tt.wantError) } } else if tt.wantError != "" { t.Errorf("%s: succeeded, but want error string %q", tt.name, tt.wantError) } }) } }
crypto/ssh/client_test.go/0
{ "file_path": "crypto/ssh/client_test.go", "repo_id": "crypto", "token_count": 3908 }
13
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh // Message authentication support import ( "crypto/hmac" "crypto/sha1" "crypto/sha256" "crypto/sha512" "hash" ) type macMode struct { keySize int etm bool new func(key []byte) hash.Hash } // truncatingMAC wraps around a hash.Hash and truncates the output digest to // a given size. type truncatingMAC struct { length int hmac hash.Hash } func (t truncatingMAC) Write(data []byte) (int, error) { return t.hmac.Write(data) } func (t truncatingMAC) Sum(in []byte) []byte { out := t.hmac.Sum(in) return out[:len(in)+t.length] } func (t truncatingMAC) Reset() { t.hmac.Reset() } func (t truncatingMAC) Size() int { return t.length } func (t truncatingMAC) BlockSize() int { return t.hmac.BlockSize() } var macModes = map[string]*macMode{ "hmac-sha2-512-etm@openssh.com": {64, true, func(key []byte) hash.Hash { return hmac.New(sha512.New, key) }}, "hmac-sha2-256-etm@openssh.com": {32, true, func(key []byte) hash.Hash { return hmac.New(sha256.New, key) }}, "hmac-sha2-512": {64, false, func(key []byte) hash.Hash { return hmac.New(sha512.New, key) }}, "hmac-sha2-256": {32, false, func(key []byte) hash.Hash { return hmac.New(sha256.New, key) }}, "hmac-sha1": {20, false, func(key []byte) hash.Hash { return hmac.New(sha1.New, key) }}, "hmac-sha1-96": {20, false, func(key []byte) hash.Hash { return truncatingMAC{12, hmac.New(sha1.New, key)} }}, }
crypto/ssh/mac.go/0
{ "file_path": "crypto/ssh/mac.go", "repo_id": "crypto", "token_count": 647 }
14
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package terminal provides support functions for dealing with terminals, as // commonly found on UNIX systems. // // Deprecated: this package moved to golang.org/x/term. package terminal import ( "io" "golang.org/x/term" ) // EscapeCodes contains escape sequences that can be written to the terminal in // order to achieve different styles of text. type EscapeCodes = term.EscapeCodes // Terminal contains the state for running a VT100 terminal that is capable of // reading lines of input. type Terminal = term.Terminal // NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is // a local terminal, that terminal must first have been put into raw mode. // prompt is a string that is written at the start of each input line (i.e. // "> "). func NewTerminal(c io.ReadWriter, prompt string) *Terminal { return term.NewTerminal(c, prompt) } // ErrPasteIndicator may be returned from ReadLine as the error, in addition // to valid line data. It indicates that bracketed paste mode is enabled and // that the returned line consists only of pasted data. Programs may wish to // interpret pasted data more literally than typed data. var ErrPasteIndicator = term.ErrPasteIndicator // State contains the state of a terminal. type State = term.State // IsTerminal returns whether the given file descriptor is a terminal. func IsTerminal(fd int) bool { return term.IsTerminal(fd) } // ReadPassword reads a line of input from a terminal without local echo. This // is commonly used for inputting passwords and other sensitive data. The slice // returned does not include the \n. func ReadPassword(fd int) ([]byte, error) { return term.ReadPassword(fd) } // MakeRaw puts the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd int) (*State, error) { return term.MakeRaw(fd) } // Restore restores the terminal connected to the given file descriptor to a // previous state. func Restore(fd int, oldState *State) error { return term.Restore(fd, oldState) } // GetState returns the current state of a terminal which may be useful to // restore the terminal after a signal. func GetState(fd int) (*State, error) { return term.GetState(fd) } // GetSize returns the dimensions of the given terminal. func GetSize(fd int) (width, height int, err error) { return term.GetSize(fd) }
crypto/ssh/terminal/terminal.go/0
{ "file_path": "crypto/ssh/terminal/terminal.go", "repo_id": "crypto", "token_count": 699 }
15
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // IMPLEMENTATION NOTE: To avoid a package loop, this file is in three places: // ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three // instances. package ssh import ( "crypto/rand" "fmt" "golang.org/x/crypto/ssh/testdata" ) var ( testPrivateKeys map[string]interface{} testSigners map[string]Signer testPublicKeys map[string]PublicKey ) func init() { var err error n := len(testdata.PEMBytes) testPrivateKeys = make(map[string]interface{}, n) testSigners = make(map[string]Signer, n) testPublicKeys = make(map[string]PublicKey, n) for t, k := range testdata.PEMBytes { testPrivateKeys[t], err = ParseRawPrivateKey(k) if err != nil { panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) } testSigners[t], err = NewSignerFromKey(testPrivateKeys[t]) if err != nil { panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) } testPublicKeys[t] = testSigners[t].PublicKey() } // Create a cert and sign it for use in tests. testCert := &Certificate{ Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage ValidAfter: 0, // unix epoch ValidBefore: CertTimeInfinity, // The end of currently representable time. Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil Key: testPublicKeys["ecdsa"], SignatureKey: testPublicKeys["rsa"], Permissions: Permissions{ CriticalOptions: map[string]string{}, Extensions: map[string]string{}, }, } testCert.SignCert(rand.Reader, testSigners["rsa"]) testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] testSigners["cert"], err = NewCertSigner(testCert, testSigners["ecdsa"]) if err != nil { panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) } }
crypto/ssh/testdata_test.go/0
{ "file_path": "crypto/ssh/testdata_test.go", "repo_id": "crypto", "token_count": 856 }
16
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package xts implements the XTS cipher mode as specified in IEEE P1619/D16. // // XTS mode is typically used for disk encryption, which presents a number of // novel problems that make more common modes inapplicable. The disk is // conceptually an array of sectors and we must be able to encrypt and decrypt // a sector in isolation. However, an attacker must not be able to transpose // two sectors of plaintext by transposing their ciphertext. // // XTS wraps a block cipher with Rogaway's XEX mode in order to build a // tweakable block cipher. This allows each sector to have a unique tweak and // effectively create a unique key for each sector. // // XTS does not provide any authentication. An attacker can manipulate the // ciphertext and randomise a block (16 bytes) of the plaintext. This package // does not implement ciphertext-stealing so sectors must be a multiple of 16 // bytes. // // Note that XTS is usually not appropriate for any use besides disk encryption. // Most users should use an AEAD mode like GCM (from crypto/cipher.NewGCM) instead. package xts import ( "crypto/cipher" "encoding/binary" "errors" "sync" "golang.org/x/crypto/internal/alias" ) // Cipher contains an expanded key structure. It is safe for concurrent use if // the underlying block cipher is safe for concurrent use. type Cipher struct { k1, k2 cipher.Block } // blockSize is the block size that the underlying cipher must have. XTS is // only defined for 16-byte ciphers. const blockSize = 16 var tweakPool = sync.Pool{ New: func() interface{} { return new([blockSize]byte) }, } // NewCipher creates a Cipher given a function for creating the underlying // block cipher (which must have a block size of 16 bytes). The key must be // twice the length of the underlying cipher's key. func NewCipher(cipherFunc func([]byte) (cipher.Block, error), key []byte) (c *Cipher, err error) { c = new(Cipher) if c.k1, err = cipherFunc(key[:len(key)/2]); err != nil { return } c.k2, err = cipherFunc(key[len(key)/2:]) if c.k1.BlockSize() != blockSize { err = errors.New("xts: cipher does not have a block size of 16") } return } // Encrypt encrypts a sector of plaintext and puts the result into ciphertext. // Plaintext and ciphertext must overlap entirely or not at all. // Sectors must be a multiple of 16 bytes and less than 2²⁴ bytes. func (c *Cipher) Encrypt(ciphertext, plaintext []byte, sectorNum uint64) { if len(ciphertext) < len(plaintext) { panic("xts: ciphertext is smaller than plaintext") } if len(plaintext)%blockSize != 0 { panic("xts: plaintext is not a multiple of the block size") } if alias.InexactOverlap(ciphertext[:len(plaintext)], plaintext) { panic("xts: invalid buffer overlap") } tweak := tweakPool.Get().(*[blockSize]byte) for i := range tweak { tweak[i] = 0 } binary.LittleEndian.PutUint64(tweak[:8], sectorNum) c.k2.Encrypt(tweak[:], tweak[:]) for len(plaintext) > 0 { for j := range tweak { ciphertext[j] = plaintext[j] ^ tweak[j] } c.k1.Encrypt(ciphertext, ciphertext) for j := range tweak { ciphertext[j] ^= tweak[j] } plaintext = plaintext[blockSize:] ciphertext = ciphertext[blockSize:] mul2(tweak) } tweakPool.Put(tweak) } // Decrypt decrypts a sector of ciphertext and puts the result into plaintext. // Plaintext and ciphertext must overlap entirely or not at all. // Sectors must be a multiple of 16 bytes and less than 2²⁴ bytes. func (c *Cipher) Decrypt(plaintext, ciphertext []byte, sectorNum uint64) { if len(plaintext) < len(ciphertext) { panic("xts: plaintext is smaller than ciphertext") } if len(ciphertext)%blockSize != 0 { panic("xts: ciphertext is not a multiple of the block size") } if alias.InexactOverlap(plaintext[:len(ciphertext)], ciphertext) { panic("xts: invalid buffer overlap") } tweak := tweakPool.Get().(*[blockSize]byte) for i := range tweak { tweak[i] = 0 } binary.LittleEndian.PutUint64(tweak[:8], sectorNum) c.k2.Encrypt(tweak[:], tweak[:]) for len(ciphertext) > 0 { for j := range tweak { plaintext[j] = ciphertext[j] ^ tweak[j] } c.k1.Decrypt(plaintext, plaintext) for j := range tweak { plaintext[j] ^= tweak[j] } plaintext = plaintext[blockSize:] ciphertext = ciphertext[blockSize:] mul2(tweak) } tweakPool.Put(tweak) } // mul2 multiplies tweak by 2 in GF(2¹²⁸) with an irreducible polynomial of // x¹²⁸ + x⁷ + x² + x + 1. func mul2(tweak *[blockSize]byte) { var carryIn byte for j := range tweak { carryOut := tweak[j] >> 7 tweak[j] = (tweak[j] << 1) + carryIn carryIn = carryOut } if carryIn != 0 { // If we have a carry bit then we need to subtract a multiple // of the irreducible polynomial (x¹²⁸ + x⁷ + x² + x + 1). // By dropping the carry bit, we're subtracting the x^128 term // so all that remains is to subtract x⁷ + x² + x + 1. // Subtraction (and addition) in this representation is just // XOR. tweak[0] ^= 1<<7 | 1<<2 | 1<<1 | 1 } }
crypto/xts/xts.go/0
{ "file_path": "crypto/xts/xts.go", "repo_id": "crypto", "token_count": 1772 }
17
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bytes" "fmt" "hash/fnv" "sort" "strings" ) type graphviz struct { ps []*gvnode b bytes.Buffer h map[string]uint32 // clusters is a map of project name and subgraph object. This can be used // to refer the subgraph by project name. clusters map[string]*gvsubgraph } type gvnode struct { project string version string children []string } // Sort gvnode(s). type byGvnode []gvnode func (n byGvnode) Len() int { return len(n) } func (n byGvnode) Swap(i, j int) { n[i], n[j] = n[j], n[i] } func (n byGvnode) Less(i, j int) bool { return n[i].project < n[j].project } func (g graphviz) New() *graphviz { ga := &graphviz{ ps: []*gvnode{}, h: make(map[string]uint32), clusters: make(map[string]*gvsubgraph), } return ga } func (g *graphviz) output(project string) bytes.Buffer { if project == "" { // Project relations graph. g.b.WriteString("digraph {\n\tnode [shape=box];") for _, gvp := range g.ps { // Create node string g.b.WriteString(fmt.Sprintf("\n\t%d [label=\"%s\"];", gvp.hash(), gvp.label())) } g.createProjectRelations() } else { // Project-Package relations graph. g.b.WriteString("digraph {\n\tnode [shape=box];\n\tcompound=true;\n\tedge [minlen=2];") // Declare all the nodes with labels. for _, gvp := range g.ps { g.b.WriteString(fmt.Sprintf("\n\t%d [label=\"%s\"];", gvp.hash(), gvp.label())) } // Sort the clusters for a consistent output. clusters := sortClusters(g.clusters) // Declare all the subgraphs with labels. for _, gsg := range clusters { g.b.WriteString(fmt.Sprintf("\n\tsubgraph cluster_%d {", gsg.index)) g.b.WriteString(fmt.Sprintf("\n\t\tlabel = \"%s\";", gsg.project)) nhashes := []string{} for _, pkg := range gsg.packages { nhashes = append(nhashes, fmt.Sprint(g.h[pkg])) } g.b.WriteString(fmt.Sprintf("\n\t\t%s;", strings.Join(nhashes, " "))) g.b.WriteString("\n\t}") } g.createProjectPackageRelations(project, clusters) } g.b.WriteString("\n}\n") return g.b } func (g *graphviz) createProjectRelations() { // Store relations to avoid duplication rels := make(map[string]bool) // Create relations for _, dp := range g.ps { for _, bsc := range dp.children { for pr, hsh := range g.h { if isPathPrefix(bsc, pr) { r := fmt.Sprintf("\n\t%d -> %d", g.h[dp.project], hsh) if _, ex := rels[r]; !ex { g.b.WriteString(r + ";") rels[r] = true } } } } } } func (g *graphviz) createProjectPackageRelations(project string, clusters []*gvsubgraph) { // This function takes a child package/project, target project, subgraph meta, from // and to of the edge and write a relation. linkRelation := func(child, project string, meta []string, from, to uint32) { if child == project { // Check if it's a cluster. target, ok := g.clusters[project] if ok { // It's a cluster. Point to the Project Root. Use lhead. meta = append(meta, fmt.Sprintf("lhead=cluster_%d", target.index)) // When the head points to a cluster root, use the first // node in the cluster as to. to = g.h[target.packages[0]] } } if len(meta) > 0 { g.b.WriteString(fmt.Sprintf("\n\t%d -> %d [%s];", from, to, strings.Join(meta, " "))) } else { g.b.WriteString(fmt.Sprintf("\n\t%d -> %d;", from, to)) } } // Create relations from nodes. for _, node := range g.ps { for _, child := range node.children { // Only if it points to the target project, proceed further. if isPathPrefix(child, project) { meta := []string{} from := g.h[node.project] to := g.h[child] linkRelation(child, project, meta, from, to) } } } // Create relations from clusters. for _, cluster := range clusters { for _, child := range cluster.children { // Only if it points to the target project, proceed further. if isPathPrefix(child, project) { meta := []string{fmt.Sprintf("ltail=cluster_%d", cluster.index)} // When the tail is from a cluster, use the first node in the // cluster as from. from := g.h[cluster.packages[0]] to := g.h[child] linkRelation(child, project, meta, from, to) } } } } func (g *graphviz) createNode(project, version string, children []string) { pr := &gvnode{ project: project, version: version, children: children, } g.h[pr.project] = pr.hash() g.ps = append(g.ps, pr) } func (dp gvnode) hash() uint32 { h := fnv.New32a() h.Write([]byte(dp.project)) return h.Sum32() } func (dp gvnode) label() string { label := []string{dp.project} if dp.version != "" { label = append(label, dp.version) } return strings.Join(label, "\\n") } // isPathPrefix ensures that the literal string prefix is a path tree match and // guards against possibilities like this: // // github.com/sdboyer/foo // github.com/sdboyer/foobar/baz // // Verify that prefix is path match and either the input is the same length as // the match (in which case we know they're equal), or that the next character // is a "/". (Import paths are defined to always use "/", not the OS-specific // path separator.) func isPathPrefix(path, pre string) bool { pathlen, prflen := len(path), len(pre) if pathlen < prflen || path[0:prflen] != pre { return false } return prflen == pathlen || strings.Index(path[prflen:], "/") == 0 } // gvsubgraph is a graphviz subgraph with at least one node(package) in it. type gvsubgraph struct { project string // Project root name of a project. packages []string // List of subpackages in the project. index int // Index of the subgraph cluster. This is used to refer the subgraph in the dot file. children []string // Dependencies of the project root package. } func (sg gvsubgraph) hash() uint32 { h := fnv.New32a() h.Write([]byte(sg.project)) return h.Sum32() } // createSubgraph creates a graphviz subgraph with nodes in it. This should only // be created when a project has more than one package. A single package project // should be just a single node. // First nodes are created using the provided packages and their imports. Then // a subgraph is created with all the nodes in it. func (g *graphviz) createSubgraph(project string, packages map[string][]string) { // If there's only a single package and that's the project root, do not // create a subgraph. Just create a node. if children, ok := packages[project]; ok && len(packages) == 1 { g.createNode(project, "", children) return } // Sort and use the packages for consistent output. pkgs := []gvnode{} for name, children := range packages { pkgs = append(pkgs, gvnode{project: name, children: children}) } sort.Sort(byGvnode(pkgs)) subgraphPkgs := []string{} rootChildren := []string{} for _, p := range pkgs { if p.project == project { // Do not create a separate node for the root package. rootChildren = append(rootChildren, p.children...) continue } g.createNode(p.project, "", p.children) subgraphPkgs = append(subgraphPkgs, p.project) } sg := &gvsubgraph{ project: project, packages: subgraphPkgs, index: len(g.clusters), children: rootChildren, } g.h[project] = sg.hash() g.clusters[project] = sg } // sortCluster takes a map of all the clusters and returns a list of cluster // names sorted by the cluster index. func sortClusters(clusters map[string]*gvsubgraph) []*gvsubgraph { result := []*gvsubgraph{} for _, cluster := range clusters { result = append(result, cluster) } sort.Slice(result, func(i, j int) bool { return result[i].index < result[j].index }) return result }
dep/cmd/dep/graphviz.go/0
{ "file_path": "dep/cmd/dep/graphviz.go", "repo_id": "dep", "token_count": 2965 }
18
digraph { node [shape=box]; compound=true; edge [minlen=2]; 552838292 [label="ProjectA/pkgX"]; 569615911 [label="ProjectA/pkgY"]; 2062426895 [label="ProjectB/pkgX"]; 2045649276 [label="ProjectB/pkgY"]; 990902230 [label="ProjectC/pkgX"]; 1007679849 [label="ProjectC/pkgY"]; 957346992 [label="ProjectC/pkgZ"]; subgraph cluster_0 { label = "ProjectA"; 552838292 569615911; } subgraph cluster_1 { label = "ProjectB"; 2062426895 2045649276; } subgraph cluster_2 { label = "ProjectC"; 990902230 1007679849 957346992; } 552838292 -> 957346992; 569615911 -> 990902230; 2045649276 -> 957346992; }
dep/cmd/dep/testdata/graphviz/subgraph1.dot/0
{ "file_path": "dep/cmd/dep/testdata/graphviz/subgraph1.dot", "repo_id": "dep", "token_count": 278 }
19
noverify = ["github.com/sdboyer/deptest"]
dep/cmd/dep/testdata/harness_tests/check/noverify/vendororphans/final/Gopkg.toml/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/check/noverify/vendororphans/final/Gopkg.toml", "repo_id": "dep", "token_count": 18 }
20
{ "commands": [ ["init", "-no-examples"], ["ensure", "-add", "github.com/sdboyer/deptesttres", "github.com/sdboyer/deptesttres/subp"] ], "vendor-final": [ "github.com/sdboyer/deptest", "github.com/sdboyer/deptesttres" ] }
dep/cmd/dep/testdata/harness_tests/ensure/add/all-new-double/testcase.json/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/ensure/add/all-new-double/testcase.json", "repo_id": "dep", "token_count": 123 }
21
{ "commands": [ ["ensure", "-add", "github.com/sdboyer/deptesttres@master"] ], "vendor-final": [ "github.com/sdboyer/deptest", "github.com/sdboyer/deptestdos", "github.com/sdboyer/deptesttres" ] }
dep/cmd/dep/testdata/harness_tests/ensure/add/desync/testcase.json/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/ensure/add/desync/testcase.json", "repo_id": "dep", "token_count": 114 }
22
{ "commands": [ ["ensure", "-add", "github.com/sdboyer/deptest"] ], "error-expected": "nothing to -add, github.com/sdboyer/deptest is already in Gopkg.toml and the project's direct imports or required list" }
dep/cmd/dep/testdata/harness_tests/ensure/add/errs/exists/testcase.json/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/ensure/add/errs/exists/testcase.json", "repo_id": "dep", "token_count": 81 }
23
noverify = ["github.com/sdboyer/deptest"]
dep/cmd/dep/testdata/harness_tests/ensure/noverify/hash_mismatch/initial/Gopkg.toml/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/ensure/noverify/hash_mismatch/initial/Gopkg.toml", "repo_id": "dep", "token_count": 18 }
24
ignored = ["github.com/sdboyer/deptest*", "github.com/golang/notexist/samples*"]
dep/cmd/dep/testdata/harness_tests/ensure/pkg-ignored/wildcard-other-root/final/Gopkg.toml/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/ensure/pkg-ignored/wildcard-other-root/final/Gopkg.toml", "repo_id": "dep", "token_count": 34 }
25
Ignore glide config if glide.yaml is malformed and cannot be parsed correctly.
dep/cmd/dep/testdata/harness_tests/init/glide/case4/README.md/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/init/glide/case4/README.md", "repo_id": "dep", "token_count": 19 }
26
[[constraint]] name = "github.com/ChinmayR/deptestglideA" version = "0.6.0"
dep/cmd/dep/testdata/harness_tests/init/glide/trans-trans-trans/final/Gopkg.toml/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/init/glide/trans-trans-trans/final/Gopkg.toml", "repo_id": "dep", "token_count": 39 }
27
{ "commands": [ ["init"] ], "error-expected": "init aborted: manifest already exists", "vendor-final": [] }
dep/cmd/dep/testdata/harness_tests/init/manifest-exists/testcase.json/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/init/manifest-exists/testcase.json", "repo_id": "dep", "token_count": 45 }
28
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "flag" "runtime" "github.com/golang/dep" ) var ( version = "devel" buildDate string commitHash string ) const versionHelp = `Show the dep version information` func (cmd *versionCommand) Name() string { return "version" } func (cmd *versionCommand) Args() string { return "" } func (cmd *versionCommand) ShortHelp() string { return versionHelp } func (cmd *versionCommand) LongHelp() string { return versionHelp } func (cmd *versionCommand) Hidden() bool { return false } func (cmd *versionCommand) Register(fs *flag.FlagSet) {} type versionCommand struct{} func (cmd *versionCommand) Run(ctx *dep.Ctx, args []string) error { ctx.Out.Printf(`dep: version : %s build date : %s git hash : %s go version : %s go compiler : %s platform : %s/%s features : ImportDuringSolve=%v `, version, buildDate, commitHash, runtime.Version(), runtime.Compiler, runtime.GOOS, runtime.GOARCH, importDuringSolve()) return nil }
dep/cmd/dep/version.go/0
{ "file_path": "dep/cmd/dep/version.go", "repo_id": "dep", "token_count": 377 }
29
--- id: glossary title: Glossary --- dep uses some specialized terminology. Learn about it here! * [Atom](#atom) * [Cache lock](#cache-lock) * [Constraint](#constraint) * [Current Project](#current-project) * [Deducible](#deducible) * [Deduction](#deduction) * [Direct Dependency](#direct-dependency) * [External Import](#external-import) * [GPS](#gps) * [Local cache](#local-cache) * [Lock](#lock) * [Manifest](#manifest) * [Metadata Service](#metadata-service) * [Override](#override) * [Project](#project) * [Project Root](#project-root) * [Solver](#solver) * [Source](#source) * [Source Root](#source-root) * [Sync](#sync) * [Transitive Dependency](#transitive-dependency) * [Vendor Verification](#vendor-verification) --- ### Atom Atoms are a source at a particular version. In practice, this means a two-tuple of [project root](#project-root) and version, e.g. `github.com/foo/bar@master`. Atoms are primarily internal to the [solver](#solver), and the term is rarely used elsewhere. ### Cache lock Also "cache lock file." A file, named `sm.lock`, used to ensure only a single dep process operates on the [local cache](#local-cache) at a time, as it is unsafe in dep's current design for multiple processes to access the local cache. ### Constraint Constraints have both a narrow and a looser meaning. The narrow sense refers to a [`[[constraint]]`](Gopkg.toml.md#constraint) stanza in `Gopkg.toml`. However, in some contexts, the word may be used more loosely to refer to the idea of applying rules and requirements to dependency management in general. ### Current Project The project on which dep is operating - writing its `Gopkg.lock` and populating its `vendor` directory. Also called the "root project." ### Deducible A shorthand way of referring to whether or not import path [deduction](#deduction) will return successfully for a given import path. "Undeducible" is also often used, to refer to an import path for which deduction fails. ### Deduction Deduction is the process of determining the subset of an import path that corresponds to a source root. Some patterns are known a priori (static); others must be discovered via network requests (dynamic). See the reference on [import path deduction](deduction.md) for specifics. ### Direct Dependency A project's direct dependencies are those that it _imports_ from one or more of its packages, or includes in its [`required`](Gopkg.toml.md#required) list in `Gopkg.toml`. If each letter in `A -> B -> C -> D` represents a distinct project containing only a single package, and `->` indicates an import statement, then `B` is `A`'s direct dependency, whereas `C` and `D` are [transitive dependencies](#transitive-dependency) of `A`. Dep only incorporates the `required` rules from the [current project's](#current-project) `Gopkg.toml`. Therefore, if `=>` represents `required` rather than a standard import, and `A -> B => C`, then `C` is a direct dependency of `B` _only_ when `B` is the current project. Because the `B`-to-`C` link does not exist when `A` is the current project, then `C` won't actually be in the graph at all. ### External Import An `import` statement that points to a package in a project other than the one in which it originates. For example, an `import` in package `github.com/foo/bar` will be considered an external import if it points to anything _other_ than stdlib or `github.com/foo/bar/*`. ### GPS Acronym for "Go packaging solver", it is [a subtree of library-style packages within dep](https://godoc.org/github.com/golang/dep/gps), and is the engine around which dep is built. Most commonly referred to as "gps." ### Local cache dep maintains its own, pristine set of upstream sources (so, generally, git repository clones). This is kept separate from `$GOPATH/src` so that there is no obligation to maintain disk state within `$GOPATH`, as dep frequently needs to change disk state in order to do its work. By default, the local cache lives at `$GOPATH/pkg/dep`. If you have multiple `$GOPATH` entries, dep will use whichever is the logical parent of the process' working directory. Alternatively, the location can be forced via the [`DEPCACHEDIR` environment variable](env-vars.md#depcachedir). ### Lock A generic term, used across many language package managers, for the kind of information dep keeps in a `Gopkg.lock` file. ### Manifest A generic term, used across many language package managers, for the kind of information dep keeps in a `Gopkg.toml` file. ### Metadata Service An HTTP service that, when it receives an HTTP request containing a `go-get=1` in the query string, treats interprets the path portion of the request as an import path, and responds by embedding data in HTML `<meta>` tags that indicate the type and URL of of the underlying source root. This is the server-side component of dynamic [deduction](#deduction). The behavior of metadata services is defined in the [Go documentation on remote import paths](https://golang.org/cmd/go/#hdr-Remote_import_paths). Variously referenced as "HTTP metadata service", "`go-get` HTTP metadata service", "`go-get` service", etc. ### Override An override is a [`[[override]]`](Gopkg.toml.md#override) stanza in `Gopkg.toml`. ### Project A project is a tree of Go packages. Projects cannot be nested. See [Project Root](#project-root) for more information about how the root of the tree is determined. ### Project Root The root import path for a project. A project root is defined as: * For the current project, the location of the `Gopkg.toml` file defines the project root * For dependencies, the root of the network [source](#source) (VCS repository) is treated as the project root These are generally one and the same, though not always. When using dep inside a monorepo, multiple `Gopkg.toml` files may exist at subpaths for discrete projects, designating each of those import paths as Project Roots. This works fine when working directly on those projects. If, however, any project not in the repository seeks to import the monorepo, dep will treat the monorepo as one big Project, with the root directory being the Project Root; it will disregard any and all `Gopkg.toml` files in subdirectories. This may also be referred to as the "import root" or "root import path." ### Solver "The solver" is a reference to the domain-specific SAT solver contained in [gps](#gps). More detail can be found on its [reference page](the-solver.md). ### Source The remote entities that hold versioned code. Sources are specifically the entity containing the code, not any particular version of the code itself. "Source" is used in lieu of "VCS" because Go package management tools will soon learn to use more than just VCS systems. ### Source Root The portion of an import path that corresponds to the network location of a source. This is similar to [Project Root](#project-root), but refers strictly to the second, network-oriented definition. ### Sync Dep is designed around a well-defined relationship between four states: 1. `import` statements in `.go` files 2. `Gopkg.toml` 3. `Gopkg.lock` 4. The `vendor` directory If any aspect of the relationship is unfulfilled (e.g., there is an `import` not reflected in `Gopkg.lock`, or a project that's missing from `vendor`), then dep considers the project to be "out of sync." This concept is explored in detail in [ensure mechanics](ensure-mechanics.md#staying-in-sync). ### Transitive Dependency A project's transitive dependencies are those dependencies that it does not import itself, but are imported by one of its dependencies. If each letter in `A -> B -> C -> D` represents a distinct project containing only a single package, and `->` indicates an import statement, then `C` and `D` are `A`'s transitive dependencies, whereas `B` is a [direct dependency](#transitive-dependency) of `A`. ### Vendor Verification Dep guarantees that `vendor/` contains exactly the expected code by hashing the contents of each project and storing the resulting [digest in Gopkg.lock](Gopkg.lock.md#digest). This digest is computed _after_ pruning rules are applied. The digest is used to determine if the contents of `vendor/` need to be regenerated during a `dep ensure` run, and `dep check` uses it to determine whether `Gopkg.lock` and `vendor/` are in [sync](#sync). The [`noverify`](Gopkg.toml.md#noverify) list in `Gopkg.toml` can be used to bypass most of these verification behaviors.
dep/docs/glossary.md/0
{ "file_path": "dep/docs/glossary.md", "repo_id": "dep", "token_count": 2325 }
30
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gps import ( "fmt" "math/rand" "strconv" ) // ProjectRoot is the topmost import path in a tree of other import paths - the // root of the tree. In gps' current design, ProjectRoots have to correspond to // a repository root (mostly), but their real purpose is to identify the root // import path of a "project", logically encompassing all child packages. // // Projects are a crucial unit of operation in gps. Constraints are declared by // a project's manifest, and apply to all packages in a ProjectRoot's tree. // Solving itself mostly proceeds on a project-by-project basis. // // Aliasing string types is usually a bit of an anti-pattern. gps does it here // as a means of clarifying API intent. This is important because Go's package // management domain has lots of different path-ish strings floating around: // // actual directories: // /home/sdboyer/go/src/github.com/sdboyer/gps/example // URLs: // https://github.com/sdboyer/gps // import paths: // github.com/sdboyer/gps/example // portions of import paths that refer to a package: // example // portions that could not possibly refer to anything sane: // github.com/sdboyer // portions that correspond to a repository root: // github.com/sdboyer/gps // // While not a panacea, having ProjectRoot allows gps to clearly indicate via // the type system when a path-ish string must have particular semantics. type ProjectRoot string // A ProjectIdentifier provides the name and source location of a dependency. It // is related to, but differs in two key ways from, a plain import path. // // First, ProjectIdentifiers do not identify a single package. Rather, they // encompass the whole tree of packages, including tree's root - the // ProjectRoot. In gps' current design, this ProjectRoot almost always // corresponds to the root of a repository. // // Second, ProjectIdentifiers can optionally carry a Source, which // identifies where the underlying source code can be located on the network. // These can be either a full URL, including protocol, or plain import paths. // So, these are all valid data for Source: // // github.com/sdboyer/gps // github.com/fork/gps // git@github.com:sdboyer/gps // https://github.com/sdboyer/gps // // With plain import paths, network addresses are derived purely through an // algorithm. By having an explicit network name, it becomes possible to, for // example, transparently substitute a fork for the original upstream source // repository. // // Note that gps makes no guarantees about the actual import paths contained in // a repository aligning with ImportRoot. If tools, or their users, specify an // alternate Source that contains a repository with incompatible internal // import paths, gps' solving operations will error. (gps does no import // rewriting.) // // Also note that if different projects' manifests report a different // Source for a given ImportRoot, it is a solve failure. Everyone has to // agree on where a given import path should be sourced from. // // If Source is not explicitly set, gps will derive the network address from // the ImportRoot using a similar algorithm to that utilized by `go get`. type ProjectIdentifier struct { ProjectRoot ProjectRoot Source string } // Less compares by ProjectRoot then normalized Source. func (i ProjectIdentifier) Less(j ProjectIdentifier) bool { if i.ProjectRoot < j.ProjectRoot { return true } if j.ProjectRoot < i.ProjectRoot { return false } return i.normalizedSource() < j.normalizedSource() } func (i ProjectIdentifier) eq(j ProjectIdentifier) bool { if i.ProjectRoot != j.ProjectRoot { return false } if i.Source == j.Source { return true } if (i.Source == "" && j.Source == string(j.ProjectRoot)) || (j.Source == "" && i.Source == string(i.ProjectRoot)) { return true } return false } // equiv will check if the two identifiers are "equivalent," under special // rules. // // Given that the ProjectRoots are equal (==), equivalency occurs if: // // 1. The Sources are equal (==), OR // 2. The LEFT (the receiver) Source is non-empty, and the right // Source is empty. // // *This is asymmetry in this binary relation is intentional.* It facilitates // the case where we allow for a ProjectIdentifier with an explicit Source // to match one without. func (i ProjectIdentifier) equiv(j ProjectIdentifier) bool { if i.ProjectRoot != j.ProjectRoot { return false } if i.Source == j.Source { return true } if i.Source != "" && j.Source == "" { return true } return false } func (i ProjectIdentifier) normalizedSource() string { if i.Source == "" { return string(i.ProjectRoot) } return i.Source } func (i ProjectIdentifier) String() string { if i.Source == "" || i.Source == string(i.ProjectRoot) { return string(i.ProjectRoot) } return fmt.Sprintf("%s (from %s)", i.ProjectRoot, i.Source) } func (i ProjectIdentifier) normalize() ProjectIdentifier { if i.Source == "" { i.Source = string(i.ProjectRoot) } return i } // ProjectProperties comprise the properties that can be attached to a // ProjectRoot. // // In general, these are declared in the context of a map of ProjectRoot to its // ProjectProperties; they make little sense without their corresponding // ProjectRoot. type ProjectProperties struct { Source string Constraint Constraint } // bimodalIdentifiers are used to track work to be done in the unselected queue. type bimodalIdentifier struct { id ProjectIdentifier // List of packages required within/under the ProjectIdentifier pl []string // prefv is used to indicate a 'preferred' version. This is expected to be // derived from a dep's lock data, or else is empty. prefv Version // Indicates that the bmi came from the root project originally fromRoot bool } type atom struct { id ProjectIdentifier v Version } // With a random revision and no name, collisions are...unlikely var nilpa = atom{ v: Revision(strconv.FormatInt(rand.Int63(), 36)), } type atomWithPackages struct { a atom pl []string } // bmi converts an atomWithPackages into a bimodalIdentifier. // // This is mostly intended for (read-only) trace use, so the package list slice // is not copied. It is the callers responsibility to not modify the pl slice, // lest that backpropagate and cause inconsistencies. func (awp atomWithPackages) bmi() bimodalIdentifier { return bimodalIdentifier{ id: awp.a.id, pl: awp.pl, } } // completeDep (name hopefully to change) provides the whole picture of a // dependency - the root (repo and project, since currently we assume the two // are the same) name, a constraint, and the actual packages needed that are // under that root. type completeDep struct { // The base workingConstraint workingConstraint // The specific packages required from the ProjectDep pl []string } // dependency represents an incomplete edge in the depgraph. It has a // fully-realized atom as the depender (the tail/source of the edge), and a set // of requirements that any atom to be attached at the head/target must satisfy. type dependency struct { depender atom dep completeDep }
dep/gps/identifier.go/0
{ "file_path": "dep/gps/identifier.go", "repo_id": "dep", "token_count": 2059 }
31
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
6
Edit dataset card