// CreateActivityWithInfo creates an activity, re-using a previous activity if // available. func (s *sqlite) CreateActivityWithInfo(ctx context.Context, filename string, gpsTrack io.Reader, activityInfo *doarama.ActivityInfo) (*doarama.Activity, error) { content, err := ioutil.ReadAll(gpsTrack) if err != nil { return nil, err } gpsTrackSha256 := sha256.Sum256(content) activityInfoSha256 := sha256.Sum256(structhash.Dump(activityInfo, 0)) var activityID int switch err := s.queryStmt.QueryRow(gpsTrackSha256[:], activityInfoSha256[:]).Scan(&activityID); err { case nil: return &doarama.Activity{ Client: s.client, ID: activityID, }, nil case sql.ErrNoRows: activity, err := s.client.CreateActivityWithInfo(ctx, filename, bytes.NewBuffer(content), activityInfo) if err != nil { return activity, err } _, err = s.insertStmt.Exec(activity.ID, gpsTrackSha256[:], activityInfoSha256[:]) return activity, err default: return nil, err } }
func main() { length := len(os.Args) if length > 2 { if os.Args[2] == "-384" { c1 := sha512.Sum384([]byte(os.Args[1])) fmt.Printf("%s\n%x\n%T\n", os.Args[1], c1, c1) } else if os.Args[2] == "-512" { c1 := sha512.Sum512([]byte(os.Args[1])) fmt.Printf("%s\n%x\n%T\n", os.Args[1], c1, c1) } else { c1 := sha256.Sum256([]byte(os.Args[1])) fmt.Printf("%s\n%x\n%T\n", os.Args[1], c1, c1) } } else if length == 2 { c1 := sha256.Sum256([]byte(os.Args[1])) fmt.Printf("%s\n%x\n%T\n", os.Args[1], c1, c1) } else { fmt.Printf("less arguments") } // Output: // 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881 // 4b68ab3847feda7d6c62c1fbcbeebfa35eab7351ed5e78f4ddadea5df64b8015 // false // [32]uint8 }
func (c *DBCredentials) buildMasterKey(db *Database) ([]byte, error) { masterKey, err := c.buildCompositeKey() if err != nil { return nil, err } block, err := aes.NewCipher(db.Headers.TransformSeed) if err != nil { return nil, err } // http://crypto.stackexchange.com/questions/21048/can-i-simulate-iterated-aes-ecb-with-other-block-cipher-modes for i := uint64(0); i < db.Headers.TransformRounds; i++ { result := make([]byte, 16) crypter := cipher.NewCBCEncrypter(block, result) crypter.CryptBlocks(masterKey[:16], masterKey[:16]) crypter = cipher.NewCBCEncrypter(block, result) crypter.CryptBlocks(masterKey[16:], masterKey[16:]) } tmp := sha256.Sum256(masterKey) masterKey = tmp[:] masterKey = append(db.Headers.MasterSeed, masterKey...) masterHash := sha256.Sum256(masterKey) masterKey = masterHash[:] return masterKey, nil }
func main() { flag.Parse() if *logTimestamps { logInfo.SetFlags(3) logError.SetFlags(3) } userhash = sha256.Sum256([]byte(*user)) passhash = sha256.Sum256([]byte(*pass)) logInfo.Println("starting redirector from", *outerAddress, "to", *innerAddress) if *useAuth { logInfo.Println("HTTP Basic Auth enabled") http.HandleFunc("/", redirectAfterAuthCheck) } else { logInfo.Println("HTTP Basic Auth disabled") http.HandleFunc("/", performRedirect) } useTLS := *crt != "" && *key != "" if useTLS { logInfo.Println("TLS enabled") logError.Fatal(http.ListenAndServeTLS(*outerAddress, *crt, *key, nil)) } else { logInfo.Println("TLS disabled") logError.Fatal(http.ListenAndServe(*outerAddress, nil)) } }
// Shad Double Sha256 Hash; sha256(sha256(data)) func Shad(data []byte) interfaces.IHash { h1 := sha256.Sum256(data) h2 := sha256.Sum256(h1[:]) h := new(Hash) h.SetBytes(h2[:]) return h }
func main() { c1 := sha256.Sum256([]byte("now is the time")) c2 := sha256.Sum256([]byte("Bobs your uncle")) fmt.Printf("%x\n%x\n%t\n%T\n", c1, c2, c1 == c2, c1) c3 := [32]uint8{} for i := 0; i < len(c1); i++ { c3[i] = c1[i] ^ c2[i] } fmt.Printf("%x\n", c3) var count int for i := 0; i < len(c3); i++ { count = count + popcount.PopCountByte(c3[i]) fmt.Printf("Popcount of byte %d is (%b) is %d\n", i, c3[i], popcount.PopCountByte(c3[i])) } fmt.Printf("Population count is %d\n", count) // Output: // 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881 // 4b68ab3847feda7d6c62c1fbcbeebfa35eab7351ed5e78f4ddadea5df64b8015 // false // [32]uint8 }
func main() { hash1 := sha256.Sum256([]byte("hello world")) hash2 := sha256.Sum256([]byte("hello worlD")) printHash(hash1) printHash(hash2) fmt.Println(diffBits(hash1, hash2)) }
// MakeSubprin computes the hash of a QEMU/KVM CoreOS image to get a // subprincipal for authorization purposes. func (lkcf *LinuxKVMCoreOSFactory) NewHostedProgram(spec HostedProgramSpec) (child HostedProgram, err error) { // (id uint, image string, uid, gid int) (auth.SubPrin, string, error) { // TODO(tmroeder): the combination of TeeReader and ReadAll doesn't seem // to copy the entire image, so we're going to hash in place for now. // This needs to be fixed to copy the image so we can avoid a TOCTTOU // attack. // TODO(kwalsh) why is this recomputed for each hosted program? b, err := ioutil.ReadFile(lkcf.Cfg.ImageFile) if err != nil { return } h := sha256.Sum256(b) bb, err := ioutil.ReadFile(spec.Path) if err != nil { return } hh := sha256.Sum256(bb) // vet things child = &KvmCoreOSContainer{ spec: spec, FactoryHash: h[:], Hash: hh[:], Factory: lkcf, Done: make(chan bool, 1), } return }
//GetAddress returns bitcoin address from PublicKey func (pub *PublicKey) GetAddress() (string, []byte) { var publicKeyPrefix byte if pub.isTestnet { publicKeyPrefix = 0x6F } else { publicKeyPrefix = 0x00 } //Next we get a sha256 hash of the public key generated //via ECDSA, and then get a ripemd160 hash of the sha256 hash. var shadPublicKeyBytes [32]byte if pub.isCompressed { shadPublicKeyBytes = sha256.Sum256(pub.key.SerializeCompressed()) } else { shadPublicKeyBytes = sha256.Sum256(pub.key.SerializeUncompressed()) } ripeHash := ripemd160.New() ripeHash.Write(shadPublicKeyBytes[:]) ripeHashedBytes := ripeHash.Sum(nil) publicKeyEncoded := base58check.Encode(publicKeyPrefix, ripeHashedBytes) return publicKeyEncoded, ripeHashedBytes }
func CalcRootHash() { e0, err := base64.StdEncoding.DecodeString(Entry0) if err != nil { log.Fatal(err) } h0 := sha256.Sum256(e0) e1, err := base64.StdEncoding.DecodeString(Entry1) if err != nil { log.Fatal(err) } h1 := sha256.Sum256(e1) e2, err := base64.StdEncoding.DecodeString(Entry2) if err != nil { log.Fatal(err) } h2 := sha256.Sum256(e2) e3, err := base64.StdEncoding.DecodeString(Entry3) if err != nil { log.Fatal(err) } h3 := sha256.Sum256(e3) hash01 := makeParent(h0[:], h1[:]) hash23 := makeParent(h2[:], h3[:]) root := makeParent(hash01[:], hash23[:]) log.Println(base64.StdEncoding.EncodeToString(root[:])) }
// AddFromRequest creates an entry from a OCSP request and adds it to // the cache, a set of upstream OCSP responders can be provided func (c *EntryCache) AddFromRequest(req *ocsp.Request, upstream []string) ([]byte, error) { e := NewEntry(c.log, c.clk) e.serial = req.SerialNumber var err error e.request, err = req.Marshal() if err != nil { return nil, err } e.responders = upstream serialHash := sha256.Sum256(e.serial.Bytes()) key := sha256.Sum256(append(append(req.IssuerNameHash, req.IssuerKeyHash...), serialHash[:]...)) e.name = fmt.Sprintf("%X", key) e.issuer = c.issuers.getFromRequest(req.IssuerNameHash, req.IssuerKeyHash) if e.issuer == nil { return nil, errors.New("No issuer in cache for request") } ctx, cancel := context.WithTimeout(context.Background(), c.requestTimeout) defer cancel() err = e.init(ctx, c.StableBackings, c.client) if err != nil { return nil, err } c.addSingle(e, key) return e.response, nil }
func encodeBase58Check(val []byte) []byte { const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" // payload p := make([]byte, 1+len(val)) // version byte (0x00) + val copy(p[1:], val) h1 := sha256.Sum256(p) h2 := sha256.Sum256(h1[:]) // value as []byte v := make([]byte, len(p)+4) // payload + first 4 bytes of h2 copy(v, p) copy(v[len(p):], h2[:4]) var res []byte x := new(big.Int).SetBytes(v) y := big.NewInt(58) m, zero := new(big.Int), new(big.Int) // convert to base58 for x.Cmp(zero) > 0 { x, m = x.DivMod(x, y, m) res = append(res, alphabet[m.Int64()]) } // append '1' for each leading zero byte in value for i := 0; v[i] == 0; i++ { res = append(res, alphabet[0]) } // reverse for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 { res[i], res[j] = res[j], res[i] } return res }
func CountSha() { c1 := sha256.Sum256([]byte("x")) c2 := sha256.Sum256([]byte("X")) fmt.Printf("%x\n%x\n%t\n%T\n", c1, c2, c1 == c2, c1) }
func main() { sha1 := sha256.Sum256([]byte(s1)) sha2 := sha256.Sum256([]byte(s2)) fmt.Println("sha1:", sha1) fmt.Println("sha2:", sha2) fmt.Println("bits:", countBits(&sha1, &sha2)) }
// MakeSubprin computes the hash of a QEMU/KVM CoreOS image to get a // subprincipal for authorization purposes. func (lkcf *LinuxKVMCoreOSHostFactory) NewHostedProgram(spec HostedProgramSpec) (child HostedProgram, err error) { // (id uint, image string, uid, gid int) (auth.SubPrin, string, error) // The args must contain the directory to write the linux_host into, as // well as the port to use for SSH. if len(spec.Args) != 3 { glog.Errorf("Expected %d args, but got %d", 3, len(spec.Args)) for i, a := range spec.Args { glog.Errorf("Arg %d: %s", i, a) } err = errors.New("KVM/CoreOS guest Tao requires args: <linux_host image> <temp directory for linux_host> <SSH port>") return } // TODO(tmroeder): the combination of TeeReader and ReadAll doesn't seem // to copy the entire image, so we're going to hash in place for now. // This needs to be fixed to copy the image so we can avoid a TOCTTOU // attack. // TODO(kwalsh) why is this recomputed for each hosted program? // TODO(kwalsh) Move this hash to LinuxKVMCoreOSHostFactory? b, err := ioutil.ReadFile(lkcf.Cfg.ImageFile) if err != nil { return } h := sha256.Sum256(b) bb, err := ioutil.ReadFile(spec.Path) if err != nil { return } hh := sha256.Sum256(bb) sockName := randName() + ".sock" sockPath := path.Join(lkcf.SocketPath, sockName) sshCfg := lkcf.Cfg.SSHKeysCfg + "\n - " + string(lkcf.PublicKey) cfg := &CoreOSLinuxhostConfig{ Name: randName(), ImageFile: lkcf.Cfg.ImageFile, // the VM image Memory: lkcf.Cfg.Memory, RulesPath: lkcf.Cfg.RulesPath, SSHKeysCfg: sshCfg, SocketPath: sockPath, } child = &KvmCoreOSHostContainer{ HostedProgramInfo: HostedProgramInfo{ spec: spec, // TODO(kwalsh) why does Id appear twice in subprin? subprin: append(FormatCoreOSLinuxhostSubprin(spec.Id, h[:]), FormatLinuxHostSubprin(spec.Id, hh[:])...), Done: make(chan bool, 1), }, Cfg: cfg, CoreOSHash: h[:], LHHash: hh[:], Factory: lkcf, } return }
// This function validates the user privided token // It calculates 3 different tokens. The current one, one before now and one after now. // The difference is driven by the TOTP step size // Based on which of the 3 steps it succeeds to validates, the client offset is updated. // It also updates the total amount of verification failures and the last time a verification happened in UTC time // Returns an error in case of verification failure, with the reason // There is a very basic method which protects from timing attacks, although if the step time used is low it should not be necessary // An attacker can still learn the synchronization offset. This is however irrelevant because the attacker has then 30 seconds to // guess the code and after 3 failures the function returns an error for the following 5 minutes func (otp *Totp) Validate(userCode string) error { // check Totp initialization if err := totpHasBeenInitialized(otp); err != nil { return err } // verify that the token is valid if userCode == "" { return errors.New("User provided token is empty") } // check against the total amount of failures if otp.totalVerificationFailures >= max_failures && !validBackoffTime(otp.lastVerificationTime) { return LockDownError } if otp.totalVerificationFailures >= max_failures && validBackoffTime(otp.lastVerificationTime) { // reset the total verification failures counter otp.totalVerificationFailures = 0 } // calculate the sha256 of the user code userTokenHash := sha256.Sum256([]byte(userCode)) userToken := hex.EncodeToString(userTokenHash[:]) // 1 calculate the 3 tokens tokens := make([]string, 3) token0Hash := sha256.Sum256([]byte(calculateTOTP(otp, -1))) token1Hash := sha256.Sum256([]byte(calculateTOTP(otp, 0))) token2Hash := sha256.Sum256([]byte(calculateTOTP(otp, 1))) tokens[0] = hex.EncodeToString(token0Hash[:]) // 30 seconds ago token tokens[1] = hex.EncodeToString(token1Hash[:]) // current token tokens[2] = hex.EncodeToString(token2Hash[:]) // next 30 seconds token // if the current time token is valid then, no need to re-sync and return nil if tokens[1] == userToken { return nil } // if the 30 seconds ago token is valid then return nil, but re-synchronize if tokens[0] == userToken { otp.synchronizeCounter(-1) return nil } // if the let's say 30 seconds ago token is valid then return nil, but re-synchronize if tokens[2] == userToken { otp.synchronizeCounter(1) return nil } otp.totalVerificationFailures++ otp.lastVerificationTime = time.Now().UTC() // important to have it in UTC // if we got here everything is good return errors.New("Tokens mismatch.") }
func main() { c1 := sha256.Sum256([]byte("x")) c2 := sha256.Sum256([]byte("X")) fmt.Printf("c1==%v\nc2==%v\n", c1, c2) fmt.Printf("Different bit count: %v\n", diffCount(c1, c2)) }
func makeKey(passphrase string, salt []byte, iter uint32) ([]byte, []byte) { h := sha256.Sum256(append([]byte(passphrase), salt...)) for i := uint32(0); i < iter; i++ { h = sha256.Sum256(h[:]) } phash := sha256.Sum256(h[:]) return h[:], phash[:] }
func diffBitSha256(data1, data2 string) int { c1 := sha256.Sum256([]byte(data1)) c2 := sha256.Sum256([]byte(data2)) diff := xor(c1, c2) return PopCount(diff[0:len(diff)]) }
func hashEntry(h hash.Hash, name, pkiBytes []byte, serial *big.Int) ([32]byte, error) { issuerNameHash, issuerKeyHash, err := common.HashNameAndPKI(h, name, pkiBytes) if err != nil { return [32]byte{}, err } serialHash := sha256.Sum256(serial.Bytes()) return sha256.Sum256(append(append(issuerNameHash, issuerKeyHash...), serialHash[:]...)), nil }
func base58CheckEncode(b []byte) string { var for_b58enc bytes.Buffer hash1 := sha256.Sum256(b) hash2 := sha256.Sum256(hash1[:]) for_b58enc.Write(b) for_b58enc.Write(hash2[0:4]) return base58Encode(for_b58enc.Bytes()) }
func (s *state) update() { if s.nonce == nil { s.nonce = new([lenNonce]byte) io.ReadFull(rand.Reader, s.nonce[:]) } if s.pktNoncePrefix == nil { s.pktNoncePrefix = new([16]byte) io.ReadFull(rand.Reader, s.pktNoncePrefix[:]) } // generate a local line Key if s.localLineKey == nil { s.localLineKey, _ = generateKey() } // generate mac key base if s.macKeyBase == nil && s.localKey.CanSign() && s.remoteKey.CanEncrypt() { s.macKeyBase = new([lenKey]byte) box.Precompute(s.macKeyBase, s.remoteKey.pub, s.localKey.prv) } // make local token if s.localToken == nil && s.localLineKey != nil { s.localToken = new(cipherset.Token) sha := sha256.Sum256((*s.localLineKey.pub)[:lenToken]) copy((*s.localToken)[:], sha[:lenToken]) } // make remote token if s.remoteToken == nil && s.remoteLineKey != nil { s.remoteToken = new(cipherset.Token) sha := sha256.Sum256((*s.remoteLineKey.pub)[:lenToken]) copy((*s.remoteToken)[:], sha[:lenToken]) } // generate line keys if s.localToken != nil && s.remoteToken != nil && (s.lineEncryptionKey == nil || s.lineDecryptionKey == nil) { var sharedKey [lenKey]byte box.Precompute(&sharedKey, s.remoteLineKey.pub, s.localLineKey.prv) sha := sha256.New() s.lineEncryptionKey = new([lenKey]byte) sha.Write(sharedKey[:]) sha.Write(s.localLineKey.pub[:]) sha.Write(s.remoteLineKey.pub[:]) sha.Sum((*s.lineEncryptionKey)[:0]) sha.Reset() s.lineDecryptionKey = new([lenKey]byte) sha.Write(sharedKey[:]) sha.Write(s.remoteLineKey.pub[:]) sha.Write(s.localLineKey.pub[:]) sha.Sum((*s.lineDecryptionKey)[:0]) } }
func main() { c1 := sha256.Sum256([]byte("x")) c2 := sha256.Sum256([]byte("X")) cDiff := 0 for i := 0; i < sha256.Size; i++ { cDiff += popcount(int(c1[i] & c2[i])) } fmt.Printf("%v\n", cDiff) }
func main() { c1 := sha256.Sum256([]byte("x")) c2 := sha256.Sum256([]byte("X")) fmt.Printf("%x\n%x\n%t\n%T\n", c1, c2, c1 == c2, c1) fmt.Printf("c1==%v\nc2==%v\n", c1, c2) }
func main() { c1 := sha256.Sum256([]byte("x")) c2 := sha256.Sum256([]byte("X")) fmt.Printf("%x\n%x\n%d\n", c1, c2, diff(c1, c2)) // Output: // 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881 // 4b68ab3847feda7d6c62c1fbcbeebfa35eab7351ed5e78f4ddadea5df64b8015 // 131 }
func DifferentBitCountInSha256(b1, b2 []byte) int { s1 := sha256.Sum256(b1) s2 := sha256.Sum256(b2) sum := 0 for i := 0; i < len(s1); i++ { sum += popCount(uint64(s1[i] ^ s2[i])) } return sum }
func WriteDOTFile(crawlResults *list.List, renderResults map[string]string) { fo, err := os.Create("result.dot") if err != nil { panic(err) } w := bufio.NewWriter(fo) w.WriteString("digraph {\n") w.WriteString(" node [shape=box];\n") urlsWithImages := make(map[string]string) for k, v := range renderResults { fmt.Printf("render:%s:%s\n", k, v) hash_bytes := sha256.Sum256([]byte(k)) hash := hex.EncodeToString(hash_bytes[:32]) urlsWithImages[hash] = k // TODO(nnielsen): Support remote mode. localFile := "file:///" path := "" if strings.HasPrefix(v, localFile) { path = v[len(localFile):] } w.WriteString(" X" + hash + " [label=\"\" image=\"" + path + "\"];\n") } for e := crawlResults.Front(); e != nil; e = e.Next() { from := e.Value.(Edge).From from_hash_bytes := sha256.Sum256([]byte(from)) from_hash := hex.EncodeToString(from_hash_bytes[:32]) to := e.Value.(Edge).To to_hash_bytes := sha256.Sum256([]byte(to)) to_hash := hex.EncodeToString(to_hash_bytes[:32]) if _, ok := urlsWithImages[to_hash]; !ok { continue } if _, ok := urlsWithImages[from_hash]; !ok { continue } w.WriteString(" X" + from_hash + " -> X" + to_hash + ";\n") } w.WriteString("}\n") w.Flush() fo.Close() fmt.Println("Results written to 'result.dot'") }
func TestPubKeyToAddressHash(t *testing.T) { p, _ := GenerateKeyPair() h := p.ToAddressHash() // Should be Ripemd160(SHA256(SHA256())) x := sha256.Sum256(p[:]) x = sha256.Sum256(x[:]) rh := ripemd160.New() rh.Write(x[:]) y := rh.Sum(nil) assert.True(t, bytes.Equal(h[:], y)) }
func main() { c1 := sha256.Sum256([]byte("x")) c1BitsSet := numBitsSet(&c1) c2 := sha256.Sum256([]byte("X")) c2BitsSet := numBitsSet(&c2) fmt.Printf("digest type: %T\n", c1) fmt.Printf("c1: %x (bits set: %d)\n", c1, c1BitsSet) fmt.Printf("c2: %x (bits set: %d)\n", c2, c2BitsSet) dif := c2BitsSet - c1BitsSet fmt.Printf("hashes of 'x' and 'X' differ by %d bits\n", dif) }
func main() { c1 := sha256.Sum256([]byte("x")) c2 := sha256.Sum256([]byte("X")) count := countDiffBits(c1, c2) fmt.Printf("%x\n%x\n", c1, c2) fmt.Printf("diff=%d\n", count) }