// create handling the creation of a new character // curl -H "Content-Type: application/json" -X POST -d '{"name":"asdf"}' http://localhost:8989 func create(c *gin.Context) { var newName struct { Name string `json:"name"` } ch := NewCharacter{} if err := c.BindJSON(&newName); err != nil { c.JSON(http.StatusBadRequest, ErrorResponse{"error while binding newName:" + err.Error()}) return } checkSum := sha1.Sum([]byte(newName.Name)) ch.CharacterID = fmt.Sprintf("%x", checkSum) char := createCharacter(ch.CharacterID, newName.Name) log.Println("Saving character:", char) err := mdb.Save(char) if err != nil { c.JSON(http.StatusBadRequest, ErrorResponse{"error while saving character:" + err.Error()}) return } c.JSON(http.StatusCreated, char) }
func ProcessAccountOverviewPassword(res http.ResponseWriter, req *http.Request, base *BaseController) { new_password := req.PostFormValue("newpassword") old_password := req.PostFormValue("oldpassword") if len(new_password) > 30 || len(new_password) < 5 { base.Session.SetFlash("Your password should have between 5 - 30 characters!", "error") http.Redirect(res, req, "/account/manage/overview/password", 301) return } if new_password != req.PostFormValue("newpassword2") { base.Session.SetFlash("The new passwords do not match!", "error") http.Redirect(res, req, "/account/manage/overview/password", 301) return } old_password_sha1 := fmt.Sprintf("%x", sha1.Sum([]byte(old_password))) if old_password_sha1 != base.Account.Password { base.Session.SetFlash("Current password is not correct", "error") http.Redirect(res, req, "/account/manage/overview/password", 301) return } err := models.ChangeAccountPassword(base.Account.Id, fmt.Sprintf("%x", sha1.Sum([]byte(new_password)))) if err != nil { http.Error(res, "Error while trying to change password", 500) return } views.Parser.ExecuteTemplate(res, "account_overview_password_success.html", &AccountOverviewPasswordSuccessResponse{"account-manage"}) }
func (c *keyManagementContext) calculateDHSessionKeys(ourKeyID, theirKeyID uint32) (sessionKeys, error) { var ret sessionKeys var sendbyte, recvbyte byte ourPrivKey, ourPubKey, err := c.pickOurKeys(ourKeyID) if err != nil { return ret, err } theirPubKey, err := c.pickTheirKey(theirKeyID) if err != nil { return ret, err } if gt(ourPubKey, theirPubKey) { //we are high end sendbyte, recvbyte = 0x01, 0x02 } else { //we are low end sendbyte, recvbyte = 0x02, 0x01 } s := new(big.Int).Exp(theirPubKey, ourPrivKey, p) secbytes := appendMPI(nil, s) sha := sha1.New() copy(ret.sendingAESKey[:], h(sendbyte, secbytes, sha)) copy(ret.receivingAESKey[:], h(recvbyte, secbytes, sha)) ret.sendingMACKey = sha1.Sum(ret.sendingAESKey[:]) ret.receivingMACKey = sha1.Sum(ret.receivingAESKey[:]) c.macKeyHistory.addKeys(ourKeyID, theirKeyID, ret.sendingMACKey, ret.receivingMACKey) return ret, nil }
// KeyVerify verifies that a key certification request was genuinely // provided by the TPM. It takes the certification data, certification // validation blob, the public half of the AIK, the public half of the key // to be certified and the nonce used in the original quote request. It then // verifies that the validation block is a valid signature for the // certification data, that the certification data matches the certified key // and that the secrets are the same (in order to avoid replay attacks). It // returns an error if any stage of the validation fails. func KeyVerify(data []byte, validation []byte, aikpub []byte, keypub []byte, secret []byte) error { n := big.NewInt(0) n.SetBytes(aikpub) e := 65537 pKey := rsa.PublicKey{N: n, E: int(e)} dataHash := sha1.Sum(data[:]) err := rsa.VerifyPKCS1v15(&pKey, crypto.SHA1, dataHash[:], validation) if err != nil { return err } keyHash := data[43:63] nonceHash := data[63:83] secretHash := sha1.Sum(secret[:]) if bytes.Equal(secretHash[:], nonceHash) == false { return fmt.Errorf("Secret doesn't match") } certHash := sha1.Sum(keypub[:]) if bytes.Equal(certHash[:], keyHash) == false { return fmt.Errorf("Key doesn't match") } return nil }
func scramble(encoded_salt, pass string) (scramble []byte, err error) { /* ================================================================== According to: http://tarantool.org/doc/dev_guide/box-protocol.html salt = base64_decode(encoded_salt); step_1 = sha1(password); step_2 = sha1(step_1); step_3 = sha1(salt, step_2); scramble = xor(step_1, step_3); return scramble; ===================================================================== */ scrambleSize := sha1.Size // == 20 salt, err := base64.StdEncoding.DecodeString(encoded_salt) if err != nil { return } step_1 := sha1.Sum([]byte(pass)) step_2 := sha1.Sum(step_1[0:]) hash := sha1.New() // may be create it once per connection ? hash.Write(salt[0:scrambleSize]) hash.Write(step_2[0:]) step_3 := hash.Sum(nil) return xor(step_1[0:], step_3[0:], scrambleSize), nil }
func calculateDHSessionKeys(ourPrivKey, ourPubKey, theirPubKey *big.Int) sessionKeys { var ret sessionKeys var sendbyte, recvbyte byte if gt(ourPubKey, theirPubKey) { //we are high end sendbyte, recvbyte = 0x01, 0x02 } else { //we are low end sendbyte, recvbyte = 0x02, 0x01 } s := new(big.Int).Exp(theirPubKey, ourPrivKey, p) secbytes := appendMPI(nil, s) sha := sha1.New() copy(ret.sendingAESKey[:], h(sendbyte, secbytes, sha)) copy(ret.receivingAESKey[:], h(recvbyte, secbytes, sha)) ret.sendingMACKey = sha1.Sum(ret.sendingAESKey[:]) ret.receivingMACKey = sha1.Sum(ret.receivingAESKey[:]) copy(ret.extraKey[:], h(0xFF, secbytes, sha256.New())) return ret }
// QuoteVerify verifies that a quote was genuinely provided by the TPM. It // takes the quote data, quote validation blob, public half of the AIK, // current PCR values and the nonce used in the original quote request. It // then verifies that the validation block is a valid signature for the // quote data, that the secrets are the same (in order to avoid replay // attacks), and that the PCR values are the same. It returns an error if // any stage of the validation fails. func QuoteVerify(data []byte, validation []byte, aikpub []byte, pcrvalues [][]byte, secret []byte) error { n := big.NewInt(0) n.SetBytes(aikpub) e := 65537 pKey := rsa.PublicKey{N: n, E: int(e)} dataHash := sha1.Sum(data[:]) err := rsa.VerifyPKCS1v15(&pKey, crypto.SHA1, dataHash[:], validation) if err != nil { return err } pcrHash := data[8:28] nonceHash := data[28:48] secretHash := sha1.Sum(secret[:]) if bytes.Equal(secretHash[:], nonceHash) == false { return fmt.Errorf("Secret doesn't match") } pcrComposite := []byte{0x00, 0x02, 0xff, 0xff, 0x00, 0x00, 0x01, 0x40} for i := 0; i < 16; i++ { pcrComposite = append(pcrComposite, pcrvalues[i]...) } pcrCompositeHash := sha1.Sum(pcrComposite[:]) if bytes.Equal(pcrCompositeHash[:], pcrHash) == false { return fmt.Errorf("PCR values don't match") } return nil }
func SaltedHash(pw, saltSeed string) Key { hashedPw := sha1.Sum([]byte(pw)) sha := sha1.New() hashedSalt := sha1.Sum([]byte(saltSeed)) io.WriteString(sha, hex.EncodeToString(hashedSalt[:])) io.WriteString(sha, hex.EncodeToString(hashedPw[:])) return Key(hex.EncodeToString(sha.Sum(nil)[:])) }
func HashedAndSalt(pw, saltSeed string) (Hash, Salt) { hashedPw := sha1.Sum([]byte(pw)) sha := sha1.New() hashedSalt := sha1.Sum([]byte(saltSeed)) io.WriteString(sha, hex.EncodeToString(hashedSalt[:])) io.WriteString(sha, hex.EncodeToString(hashedPw[:])) return Hash(hex.EncodeToString(sha.Sum(nil)[:])), Salt(hex.EncodeToString(hashedSalt[:])) }
func (b *BS) Put(key string, blob io.Reader) (string, error) { if key == "" { for i := 0; i < 1<<10; i++ { p := make([]byte, 16) _, err := rand.Read(p) if err != nil { return "", err } key = hex.EncodeToString(p) sum := sha1.Sum([]byte(key)) name := hex.EncodeToString(sum[:]) err = os.MkdirAll(filepath.Join(b.path, name[:2]), 0766) if err != nil { return "", err } f, err := os.OpenFile(filepath.Join(b.path, name[:2], name), os.O_CREATE|os.O_EXCL, 0666) if err != nil { if os.IsExist(err) { continue } return "", err } err = f.Close() if err != nil { return "", err } break } } sum := sha1.Sum([]byte(key)) name := hex.EncodeToString(sum[:]) err := os.MkdirAll(filepath.Join(b.path, name[:2]), 0766) if err != nil { return "", err } f, err := os.Create(filepath.Join(b.path, name[:2], name)) if err != nil { return "", err } _, err = io.Copy(f, blob) if err != nil { return "", err } err = f.Close() if err != nil { return "", err } return key, nil }
//hash is the hashed secret sent over the wire func getShare(hash string) (share, error) { for secret, s := range shares { fmt.Printf("%s\n", hash) fmt.Printf("%s\n", sha1.Sum([]byte(secret))) if hash == fmt.Sprintf("%s", sha1.Sum([]byte(secret))) { return s, nil } } return share{}, fmt.Errorf("Not a common share") }
// Extracts the value (the part of the string before the '.') from val. 'Valid' is true // if the signature is valid, otherwise false. func Unsign(val string, secret string) (str string, valid bool) { str = strings.Split(val, ".")[0] signed := Sign(str, secret) // In certain cases, information can be leaked by using a timing attack. // It takes advantage of the == operator only comparing until it finds a difference in the two strings. To prevent it, // hash both hashed strings first - this doesn't stop the timing difference, but it makes the information useless. valid = sha1.Sum([]byte(signed)) == sha1.Sum([]byte(val)) return }
func TestCachedFileStoreRead(t *testing.T) { rcp := NewRamCacheProvider(2000) for _, testFile := range tests { fs, err := mkFileStore(testFile) orig, _ := ioutil.ReadFile(testFile.path) numPieces := len(orig) / 512 if len(orig)%512 > 0 { numPieces++ } tC := rcp.NewCache("test", numPieces, 512, int64(len(orig)), fs) tC.WritePiece(orig[:512], 0) tC.WritePiece(orig[512:1024], 1) if err != nil { t.Fatal(err) } ret := make([]byte, testFile.fileLen) _, err = tC.ReadAt(ret, 0) if err != nil { t.Fatal(err) } wantedsum := sha1.Sum(orig[:testFile.fileLen]) sum1Str := hex.EncodeToString(wantedsum[0:]) gotsum := sha1.Sum(ret) sum2Str := hex.EncodeToString(gotsum[0:]) if sum1Str != sum2Str { t.Errorf("Wanted %v, got %v\n on cache read", sum1Str, sum2Str) for i := 0; i < len(ret); i++ { if ret[i] != orig[i] { log.Println("Found a difference at", i, "wanted", orig[i], "got", ret[i]) break } } } ret = make([]byte, testFile.fileLen) _, err = fs.ReadAt(ret, 0) if err != nil { t.Fatal(err) } gotsum = sha1.Sum(ret) sum2Str = hex.EncodeToString(gotsum[0:]) if sum1Str != sum2Str { t.Errorf("Wanted %v, got %v\n on filestore read", sum1Str, sum2Str) for i := 0; i < len(ret); i++ { if ret[i] != orig[i] { log.Println("Found a difference at", i, "wanted", orig[i], "got", ret[i]) break } } } fs.Close() } }
func constantTimeEquals(a string, b string) bool { // compare SHA-1 as a gatekeeper in constant time // then check that we didn't get by because of a collision aSha := sha1.Sum([]byte(a)) bSha := sha1.Sum([]byte(b)) if subtle.ConstantTimeCompare(aSha[:], bSha[:]) == 1 { // yes, this bit isn't constant, but you had to make a Sha1 collision to get here return a == b } return false }
func (s *share) createPing(secret string) []byte { buf := bytes.NewBuffer([]byte("DBIT")) err := bencode.Marshal(buf, Header{ "ping", *port, fmt.Sprintf("%s", sha1.Sum([]byte(secret))), fmt.Sprintf("%s", sha1.Sum([]byte("192.168.1.64:6667"))), }) check(err) return buf.Bytes() }
func (t *mytree) insert(pair kv) { p := t.root pf := p kb := []byte(pair.key) h := hasher.Sum(kb) bit := uint(0) var idn uint for p != nil { if p.kv != nil { break } idn = ((uint(h[(bit)>>3])) >> (bit & 7)) & FILTER pf = p p = p.next[idn] bit += BIT } if p != nil { if p.kv.key == pair.key { p.kv.value = pair.value return } kvp := p.kv p.kv = nil kvpb := []byte(kvp.key) hash0 := hasher.Sum(kvpb) var idn0 uint for { idn0 = ((uint(hash0[(bit)>>3])) >> (bit & 7)) & FILTER idn = ((uint(h[(bit)>>3])) >> (bit & 7)) & FILTER if idn == idn0 { nn := t.NewNode() p.next[idn] = nn p = nn } else { nn := t.NewNode() nn.kv = &pair nn0 := t.NewNode() nn0.kv = kvp p.next[idn0] = nn0 p.next[idn] = nn return } bit += BIT } } else { nn := t.NewNode() nn.kv = &pair pf.next[idn] = nn } }
func (s *share) createRequest(path string, index, begin, length int) []byte { b := bytes.NewBuffer([]byte("DBIT")) err := bencode.Marshal(b, Request{ "req", *port, fmt.Sprintf("%s", sha1.Sum([]byte(s.Secret))), fmt.Sprintf("%s", sha1.Sum([]byte("192.168.1.64:6667"))), path, index, begin, length, }) check(err) return b.Bytes() }
func normalizeCert(cert interface{}) string { if cert == nil { return "" } switch cert.(type) { case string: hash := sha1.Sum([]byte(strings.TrimSpace(cert.(string)))) return hex.EncodeToString(hash[:]) case *string: hash := sha1.Sum([]byte(strings.TrimSpace(*cert.(*string)))) return hex.EncodeToString(hash[:]) default: return "" } }
func (s *share) createPiece(path string, index, begin int, piece []byte) []byte { b := bytes.NewBuffer([]byte("DBIT")) err := bencode.Marshal(b, Piece{ "piece", *port, fmt.Sprintf("%s", sha1.Sum([]byte(s.Secret))), fmt.Sprintf("%s", sha1.Sum([]byte("192.168.1.64:6667"))), path, index, begin, fmt.Sprintf("%s", piece), }) check(err) return b.Bytes() }
func main() { var blobname = flag.String("blob", "aikblob", "The name of the file to create") var tpmname = flag.String("tpm", "/dev/tpm0", "The path to the TPM device to use") flag.Parse() f, err := os.OpenFile(*tpmname, os.O_RDWR, 0600) defer f.Close() if err != nil { fmt.Fprintf(os.Stderr, "Couldn't open TPM device %s: %s\n", *tpmname, err) return } // Compute the auth values as needed. var ownerAuth [20]byte ownerInput := os.Getenv(ownerAuthEnvVar) if ownerInput != "" { oa := sha1.Sum([]byte(ownerInput)) copy(ownerAuth[:], oa[:]) } var srkAuth [20]byte srkInput := os.Getenv(srkAuthEnvVar) if srkInput != "" { sa := sha1.Sum([]byte(srkInput)) copy(srkAuth[:], sa[:]) } var aikAuth [20]byte aikInput := os.Getenv(aikAuthEnvVar) if aikInput != "" { aa := sha1.Sum([]byte(aikInput)) copy(aikAuth[:], aa[:]) } // TODO(tmroeder): add support for Privacy CAs. blob, err := tpm.MakeIdentity(f, srkAuth[:], ownerAuth[:], aikAuth[:], nil, nil) if err != nil { fmt.Fprintf(os.Stderr, "Couldn't make an new AIK: %s\n", err) return } if err := ioutil.WriteFile(*blobname, blob, 0600); err != nil { fmt.Fprintf(os.Stderr, "Couldn't write to file %s: %s\n", *blobname, err) return } return }
func TestMultiWriter(t *testing.T) { sha1 := sha1.New() sink := new(bytes.Buffer) mw := MultiWriter(sha1, sink) sourceString := "My input text." source := strings.NewReader(sourceString) written, err := Copy(mw, source) if written != int64(len(sourceString)) { t.Errorf("short write of %d, not %d", written, len(sourceString)) } if err != nil { t.Errorf("unexpected error: %v", err) } sha1hex := fmt.Sprintf("%x", sha1.Sum()) if sha1hex != "01cb303fa8c30a64123067c5aa6284ba7ec2d31b" { t.Error("incorrect sha1 value") } if sink.String() != sourceString { t.Errorf("expected %q; got %q", sourceString, sink.String()) } }
func (m *Model) loadIndex(repo string, dir string) []protocol.FileInfo { id := fmt.Sprintf("%x", sha1.Sum([]byte(m.repoDirs[repo]))) name := id + ".idx.gz" name = filepath.Join(dir, name) idxf, err := os.Open(name) if err != nil { return nil } defer idxf.Close() gzr, err := gzip.NewReader(idxf) if err != nil { return nil } defer gzr.Close() var im protocol.IndexMessage err = im.DecodeXDR(gzr) if err != nil || im.Repository != repo { return nil } return im.Files }
func scriptLoadCommand(c *client) error { s := c.app.script l := s.l if len(c.args) != 2 { return ErrCmdParams } h := sha1.Sum(c.args[1]) key := hex.EncodeToString(h[0:20]) if r := l.LoadString(hack.String(c.args[1])); r != 0 { err := fmt.Errorf("%s", l.ToString(-1)) l.Pop(1) return err } else { l.PushValue(-1) l.SetGlobal(key) s.chunks[key] = struct{}{} } c.resp.writeBulk(hack.Slice(key)) return nil }
// newGitObjFromZcontent constructs a new gitObj using zcontent. // zcontent has the same format as the file of a unpacked git object. func newGitObjFromZcontent(zcontent []byte) (*gitObj, error) { // Uncompress r, err := zlib.NewReader(bytes.NewReader(zcontent)) if err != nil { return nil, err } defer r.Close() var out bytes.Buffer io.Copy(&out, r) b := out.Bytes() // Find header delimiter i := bytes.IndexByte(b, '\x00') if i <= 0 || i >= len(b) { return nil, errInvalidZcontent("no header delimiter") } // Calculate SHA1 and parse header to get oid and type, size o := gitObj{Oid: Oid(fmt.Sprintf("%040x", sha1.Sum(b))), Body: b[i+1:]} var size int if n, err := fmt.Sscanf(string(b[0:i]), "%s %d", &o.Type, &size); err != nil || n < 2 { return nil, errInvalidZcontent("illegal header + " + string(b[0:i])) } if size != len(o.Body) { return nil, errInvalidZcontent(fmt.Sprintf("body size mismatch: claimed %d, actual %d", size, len(o.Body))) } return &o, nil }
func TestLogin(t *testing.T) { conn, err := Dial(server+":7778", true) if err != nil { t.Fatal(err) } // авторизуемся с простым паролем resp, err := conn.Login("martint", "01103", "Mobile", "iPhone") conn.Close() if err != nil { t.Error(err) } // pretty.Println(resp) // т.к. две авторизации в одной сессии не пройдут, то приходится закрывать conn, err = Dial(server+":7778", true) if err != nil { t.Fatal(err) } // авторизуемся с хешом от пароля pwdHash := sha1.Sum([]byte("01103")) password := base64.StdEncoding.EncodeToString(pwdHash[:]) + "\n" resp, err = conn.Login("martint", password, "Mobile", "iPhone") conn.Close() if err != nil { t.Error(err) } // pretty.Println(resp) _ = resp }
// Returns a routeset with N *resources per namespace*. so N=1 gives about 15 routes func resourceSetup(N int) (namespaces []string, resources []string, requests []*http.Request) { namespaces = []string{"admin", "api", "site"} resources = []string{} for i := 0; i < N; i++ { sha1 := sha1.New() io.WriteString(sha1, fmt.Sprintf("%d", i)) strResource := fmt.Sprintf("%x", sha1.Sum(nil)) resources = append(resources, strResource) } for _, ns := range namespaces { for _, res := range resources { req, _ := http.NewRequest("GET", "/"+ns+"/"+res, nil) requests = append(requests, req) req, _ = http.NewRequest("POST", "/"+ns+"/"+res, nil) requests = append(requests, req) req, _ = http.NewRequest("GET", "/"+ns+"/"+res+"/3937", nil) requests = append(requests, req) req, _ = http.NewRequest("PUT", "/"+ns+"/"+res+"/3937", nil) requests = append(requests, req) req, _ = http.NewRequest("DELETE", "/"+ns+"/"+res+"/3937", nil) requests = append(requests, req) } } return }
// GetRepoStateHash returns a hash which embodies the entire current state of a repository. func (r *mockRepoForTest) GetRepoStateHash() (string, error) { repoJSON, err := json.Marshal(r) if err != nil { return "", err } return fmt.Sprintf("%x", sha1.Sum([]byte(repoJSON))), nil }
func fileSha1(path string) string { data, err := ioutil.ReadFile(path) if err != nil { panic(err) } return fmt.Sprintf("%x", sha1.Sum(data)) }
// ReadPubEK reads the public part of the endorsement key when no owner is // established. func ReadPubEK(f *os.File) ([]byte, error) { var n nonce if _, err := rand.Read(n[:]); err != nil { return nil, err } pk, d, _, err := readPubEK(f, n) if err != nil { return nil, err } // Recompute the hash of the pk and the nonce to defend against replay // attacks. b, err := pack([]interface{}{pk, n}) if err != nil { return nil, err } s := sha1.Sum(b) if subtle.ConstantTimeCompare(s[:], d[:]) != 1 { return nil, errors.New("the ReadPubEK operation failed the replay check") } return pack([]interface{}{pk}) }
// Quote produces a TPM quote for the given data under the given PCRs. It uses // AIK auth and a given AIK handle. func Quote(f *os.File, handle Handle, data []byte, pcrNums []int, aikAuth []byte) ([]byte, []byte, error) { // Run OSAP for the handle, reading a random OddOSAP for our initial // command and getting back a secret and a response. sharedSecret, osapr, err := newOSAPSession(f, etKeyHandle, handle, aikAuth) if err != nil { return nil, nil, err } defer osapr.Close(f) defer zeroBytes(sharedSecret[:]) // Hash the data to get the value to pass to quote2. hash := sha1.Sum(data) pcrSel, err := newPCRSelection(pcrNums) if err != nil { return nil, nil, err } authIn := []interface{}{ordQuote, hash, pcrSel} ca, err := newCommandAuth(osapr.AuthHandle, osapr.NonceEven, sharedSecret[:], authIn) if err != nil { return nil, nil, err } pcrc, sig, ra, ret, err := quote(f, handle, hash, pcrSel, ca) if err != nil { return nil, nil, err } // Check response authentication. raIn := []interface{}{ret, ordQuote, pcrc, sig} if err := ra.verify(ca.NonceOdd, sharedSecret[:], raIn); err != nil { return nil, nil, err } return sig, pcrc.Values, nil }