func NewAddress(version byte) (*Address, error) { addr := new(Address) addr.Version = version var err error addr.PrivateKey, err = ecdsa.GenerateKey(ec256k1.S256(), rand.Reader) if err != nil { return nil, errors.New("address.New: Error generating ecdsa encryption key") } publicKey := append(addr.PrivateKey.PublicKey.X.Bytes(), addr.PrivateKey.PublicKey.Y.Bytes()...) sha := sha512.New() sha.Write(publicKey) ripemd := ripemd160.New() ripemd.Write(sha.Sum(nil)) hash := ripemd.Sum(nil) toCheck := []byte{addr.Version} toCheck = append(toCheck, hash...) sha1, sha2 := sha512.New(), sha512.New() sha1.Write(toCheck) sha2.Write(sha1.Sum(nil)) checksum := sha2.Sum(nil)[:4] addr.Base58, err = EncodeBase58(append(toCheck, checksum...)) if err != nil { return nil, err } return addr, nil }
func ValidateNonce(payload []byte) bool { if len(payload) < 2 { return false } var offset int var nonce, trials_test uint64 var hash_test, initial_payload []byte nonce, offset = varint.Decode(payload) initial_payload = payload[offset:] sha := sha512.New() sha.Write(initial_payload) initial_hash := sha.Sum(nil) var target uint64 = MAX_UINT64 / uint64((len(payload)+PAYLOAD_LENGTH_EXTRA_BYTES+8)*AVERAGE_PROOF_OF_WORK_NONCE_TRIALS_PER_BYTE) hash_test = varint.Encode(nonce) hash_test = append(hash_test, initial_hash...) sha1, sha2 := sha512.New(), sha512.New() sha1.Write(hash_test) sha2.Write(sha1.Sum(nil)) trials_test = binary.BigEndian.Uint64(sha2.Sum(nil)[:8]) return trials_test <= target }
// newHash - gives you a newly allocated hash depending on the input algorithm. func newHash(algo string) hash.Hash { switch algo { case "sha512": return sha512.New() // Add new hashes here. default: return sha512.New() } }
// (cipher)^D mod N = plain // plivate key = {D,N} // D means 'Decription' func main() { // Generate key pair. public key {E,N} and private key {D,N} // E is 64437 https://en.wikipedia.org/wiki/65537_(number)) // size of key (bits) size := 2048 // nprimes is the number of prime of which N consists // e.g., if nprimes is 2, N = p*q. If nprimes is 3, N = p*q*r nprimes := 2 privateKey, err := rsa.GenerateKey(rand.Reader, size) if err != nil { fmt.Printf("err: %s", err) return } // N = p*q var z big.Int if privateKey.N.Cmp(z.Mul(privateKey.Primes[0], privateKey.Primes[1])) != 0 { panic("shoud not reach here") } plain := []byte("Bob loves Alice.") // A label is a byte string that is effectively bound to the ciphertext in a nonmalleable way. // http://crypto.stackexchange.com/questions/2074/rsa-oaep-input-parameters label := []byte("test") // Get public key from private key and encrypt publicKey := &privateKey.PublicKey cipherText, err := rsa.EncryptOAEP(sha512.New(), rand.Reader, publicKey, plain, label) if err != nil { fmt.Printf("Err: %s\n", err) return } fmt.Printf("Cipher: %x\n", cipherText) // Decrypt with private key plainText, err := rsa.DecryptOAEP(sha512.New(), rand.Reader, privateKey, cipherText, label) if err != nil { fmt.Printf("Err: %s\n", err) return } fmt.Printf("Plain: %s\n", plainText) }
// CertificateToDANE converts a certificate to a hex string as used in the TLSA record. func CertificateToDANE(selector, matchingType uint8, cert *x509.Certificate) string { switch matchingType { case 0: switch selector { case 0: return hex.EncodeToString(cert.Raw) case 1: return hex.EncodeToString(cert.RawSubjectPublicKeyInfo) } case 1: h := sha256.New() switch selector { case 0: return hex.EncodeToString(cert.Raw) case 1: io.WriteString(h, string(cert.RawSubjectPublicKeyInfo)) return hex.EncodeToString(h.Sum(nil)) } case 2: h := sha512.New() switch selector { case 0: return hex.EncodeToString(cert.Raw) case 1: io.WriteString(h, string(cert.RawSubjectPublicKeyInfo)) return hex.EncodeToString(h.Sum(nil)) } } return "" }
// CertificateToDANE converts a certificate to a hex string as used in the TLSA record. func CertificateToDANE(selector, matchingType uint8, cert *x509.Certificate) (string, error) { switch matchingType { case 0: switch selector { case 0: return hex.EncodeToString(cert.Raw), nil case 1: return hex.EncodeToString(cert.RawSubjectPublicKeyInfo), nil } case 1: h := sha256.New() switch selector { case 0: io.WriteString(h, string(cert.Raw)) return hex.EncodeToString(h.Sum(nil)), nil case 1: io.WriteString(h, string(cert.RawSubjectPublicKeyInfo)) return hex.EncodeToString(h.Sum(nil)), nil } case 2: h := sha512.New() switch selector { case 0: io.WriteString(h, string(cert.Raw)) return hex.EncodeToString(h.Sum(nil)), nil case 1: io.WriteString(h, string(cert.RawSubjectPublicKeyInfo)) return hex.EncodeToString(h.Sum(nil)), nil } } return "", errors.New("dns: bad TLSA MatchingType or TLSA Selector") }
func main() { for _, h := range []hash.Hash{md4.New(), md5.New(), sha1.New(), sha256.New224(), sha256.New(), sha512.New384(), sha512.New(), ripemd160.New()} { fmt.Printf("%x\n\n", h.Sum()) } }
func NewVerifier(hashes map[string]string, size int64) (*Verifier, error) { if size <= 0 { return nil, &ErrInvalidSize{size} } v := &Verifier{ hashes: make([]*Hash, 0, len(hashes)), size: size, } for algorithm, value := range hashes { h := &Hash{algorithm: algorithm, expected: value} switch algorithm { case "sha256": h.hash = sha256.New() case "sha512": h.hash = sha512.New() case "sha512_256": h.hash = sha512.New512_256() default: continue } v.hashes = append(v.hashes, h) } if len(v.hashes) == 0 { return nil, ErrNoHashes } return v, nil }
// Store takes a block and stores it in the Bucket using a // Sha1-Hash as key, wich is returned func StoreBlock(b Bucket, block []byte) (hash []byte, err error) { h := sha512.New() h.Write(block) hash = h.Sum([]byte{}) err = b.Store(hash, block) return }
// Verifies the image package integrity after it is downloaded func (img *Image) verify() error { // Makes sure the file cursor is positioned at the beginning of the file _, err := img.file.Seek(0, 0) if err != nil { return err } log.Printf("[DEBUG] Verifying image checksum...") var hasher hash.Hash switch img.ChecksumType { case "md5": hasher = md5.New() case "sha1": hasher = sha1.New() case "sha256": hasher = sha256.New() case "sha512": hasher = sha512.New() default: return fmt.Errorf("[ERROR] Crypto algorithm no supported: %s", img.ChecksumType) } _, err = io.Copy(hasher, img.file) if err != nil { return err } result := fmt.Sprintf("%x", hasher.Sum(nil)) if result != img.Checksum { return fmt.Errorf("[ERROR] Checksum does not match\n Result: %s\n Expected: %s", result, img.Checksum) } return nil }
// NewFileMeta generates a FileMeta object from the reader, using the // hash algorithms provided func NewFileMeta(r io.Reader, hashAlgorithms ...string) (FileMeta, error) { if len(hashAlgorithms) == 0 { hashAlgorithms = []string{defaultHashAlgorithm} } hashes := make(map[string]hash.Hash, len(hashAlgorithms)) for _, hashAlgorithm := range hashAlgorithms { var h hash.Hash switch hashAlgorithm { case "sha256": h = sha256.New() case "sha512": h = sha512.New() default: return FileMeta{}, fmt.Errorf("Unknown Hash Algorithm: %s", hashAlgorithm) } hashes[hashAlgorithm] = h r = io.TeeReader(r, h) } n, err := io.Copy(ioutil.Discard, r) if err != nil { return FileMeta{}, err } m := FileMeta{Length: n, Hashes: make(Hashes, len(hashes))} for hashAlgorithm, h := range hashes { m.Hashes[hashAlgorithm] = h.Sum(nil) } return m, nil }
func computeDetachedDigest(nonce []byte, plaintext []byte) []byte { hasher := sha512.New() hasher.Write(nonce) hasher.Write(plaintext) return detachedDigest(hasher.Sum(nil)) }
func main() { privateKey, err := rsa.GenerateKey(rand.Reader, 1024) if err != nil { fmt.Printf("rsa.GenerateKey: %v\n", err) return } message := "Hello World!" messageBytes := bytes.NewBufferString(message) hash := sha512.New() hash.Write(messageBytes.Bytes()) digest := hash.Sum(nil) fmt.Printf("messageBytes: %v\n", messageBytes) fmt.Printf("hash: %V\n", hash) fmt.Printf("digest: %v\n", digest) signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA512, digest) if err != nil { fmt.Printf("rsa.SignPKCS1v15 error: %v\n", err) return } fmt.Printf("signature: %v\n", signature) err = rsa.VerifyPKCS1v15(&privateKey.PublicKey, crypto.SHA512, digest, signature) if err != nil { fmt.Printf("rsa.VerifyPKCS1v15 error: %V\n", err) } fmt.Println("Signature good!") }
func (e *Engine) sha512() error { data, err := computeHash(sha512.New(), e.stack.Pop()) if err == nil { e.stack.Push(data) } return err }
// TestCannedContent exercises the input and output removing the randomness of rand func TestCannedContent(t *testing.T) { b := bytes.NewBufferString(DilbertRandom) s := NewSuiteWithDev(t, b) defer s.TearDown() res, err := http.Get(s.URL + "?challenge=pork+chop+sandwiches") s.Assert(err == nil, "http client error:", err) defer res.Body.Close() chal, seed, err := ReadResp(res.Body) s.Assert(err == nil, "response error:", err) s.Assert(chal == PorkChopSha512, "expected:", PorkChopSha512, "got:", chal) s.SanityCheck(chal, seed) // Check that the 'random' seed we got back was appropriately mixed // with the challenge s.Assert(seed != DilbertRandom, "got the raw random content") s.Assert(seed != DilbertRandomSHA1, "got the sha of random content without the challenge") expectedSum := sha512.New() io.WriteString(expectedSum, "pork chop sandwiches") io.WriteString(expectedSum, DilbertRandom) expectedSeed := fmt.Sprintf("%x", expectedSum.Sum(nil)) s.Assert(seed == expectedSeed, "expected:", expectedSeed, "got:", seed) // We can also check that the challenge was correctly written to our random device // b.Bytes() is the remainder of our buffer, and Buffer writes at the end // This also shows that we didn't write the raw request writtenBytesInHex := fmt.Sprintf("%x", string(b.Bytes())) s.Assert(PorkChopSha512 == writtenBytesInHex, "expected:", PorkChopSha512, "got:", writtenBytesInHex) }
func main() { if len(os.Args) < 2 { return } p := os.Args[1] i := big.NewInt(0) o := big.NewInt(1) h := sha512.New() for true { m := i.Bytes() m = append(m, make([]byte, 64-len(m))...) h.Write(m[:]) c := hex.EncodeToString(h.Sum(nil)) if strings.HasPrefix(c, p) { fmt.Println(hex.EncodeToString(m)) fmt.Println(c) return } i = i.Add(i, o) h.Reset() } }
func main() { if len(os.Args) < 2 { return } s := os.Args[1] m, _ := hex.DecodeString(s) h := sha512.New() h.Write(m) o := h.Sum(nil) fmt.Println("input_bit_changed", "hash_num_bits_changed", "hash_pos_bits_changed") for i := 0; i < 64; i++ { for j := 0; j < 8; j++ { var mc [64]byte copy(mc[:], m) mc[i] ^= 1 << uint(j) h.Reset() h.Write(mc[:]) bits, pos := differences(o, h.Sum(nil)) fmt.Println(i*8+j, bits, strings.Join(pos, ",")) } } }
func (ms *conversionStore) WriteACI(path string) (string, error) { f, err := os.Open(path) if err != nil { return "", err } defer f.Close() cr, err := aci.NewCompressedReader(f) if err != nil { return "", err } defer cr.Close() h := sha512.New() r := io.TeeReader(cr, h) // read the file so we can get the hash if _, err := io.Copy(ioutil.Discard, r); err != nil { return "", fmt.Errorf("error reading ACI: %v", err) } im, err := aci.ManifestFromImage(f) if err != nil { return "", err } key := ms.HashToKey(h) ms.acis[key] = &aciInfo{path: path, key: key, ImageManifest: im} return key, nil }
// Benchmark the generation of CEKs. func BenchmarkCEKGeneration(b *testing.B) { prv1, err := GenerateKey(rand.Reader) if err != nil { fmt.Println(err.Error()) b.FailNow() } prv2, err := GenerateKey(rand.Reader) if err != nil { fmt.Println(err.Error()) b.FailNow() } kek := prv1.InitializeKEK(rand.Reader, &prv2.PublicKey, KEKAES256CBCHMACSHA512, nil, sha512.New()) if kek == nil { fmt.Println("dhkam: failed to generate KEK") b.FailNow() } for i := 0; i < b.N; i++ { _, err := prv1.CEK(kek) if err != nil { fmt.Println(err.Error()) b.FailNow() } } }
// md5sha512sum returns MD5 and sha512 checksum of filename func md5sha512sum(filename string) (string, string, error) { if info, err := os.Stat(filename); err != nil { return "", "", err } else if info.IsDir() { return "", "", nil } file, err := os.Open(filename) if err != nil { return "", "", err } defer file.Close() hash5 := md5.New() hash512 := sha512.New() for buf, reader := make([]byte, bufferSize), bufio.NewReader(file); ; { n, err := reader.Read(buf) if err != nil { if err == io.EOF { break } return "", "", err } hash5.Write(buf[:n]) hash512.Write(buf[:n]) } checksum5 := fmt.Sprintf("%x", hash5.Sum(nil)) checksum512 := fmt.Sprintf("%x", hash512.Sum(nil)) fmt.Println(msgWithDate("hash computed from " + filename + " = " + checksum5)) return checksum5, checksum512, nil }
// GenerateKey generates a public/private key pair using randomness from rand. func GenerateKey(rand io.Reader) (publicKey *[PublicKeySize]byte, privateKey *[PrivateKeySize]byte, err error) { privateKey = new([64]byte) publicKey = new([32]byte) _, err = io.ReadFull(rand, privateKey[:32]) if err != nil { return nil, nil, err } h := sha512.New() h.Write(privateKey[:32]) digest := h.Sum(nil) digest[0] &= 248 digest[31] &= 127 digest[31] |= 64 var A edwards25519.ExtendedGroupElement var hBytes [32]byte copy(hBytes[:], digest) edwards25519.GeScalarMultBase(&A, &hBytes) A.ToBytes(publicKey) copy(privateKey[32:], publicKey[:]) return }
// Hash returns the hash func (s *SystemImagePart) Hash() string { hasher := sha512.New() hasher.Write([]byte(s.versionDetails)) hexdigest := hex.EncodeToString(hasher.Sum(nil)) return hexdigest }
// Checksum returns the checksum of some data, using a specified algorithm. // It only returns an error when an invalid algorithm is used. The valid ones // are MD5, SHA1, SHA224, SHA256, SHA384, SHA512, SHA3224, SHA3256, SHA3384, // and SHA3512. func Checksum(algorithm string, data []byte) (checksum string, err error) { // default var hasher hash.Hash switch strings.ToUpper(algorithm) { case "MD5": hasher = md5.New() case "SHA1": hasher = sha1.New() case "SHA224": hasher = sha256.New224() case "SHA256": hasher = sha256.New() case "SHA384": hasher = sha512.New384() case "SHA512": hasher = sha512.New() case "SHA3224": hasher = sha3.New224() case "SHA3256": hasher = sha3.New256() case "SHA3384": hasher = sha3.New384() case "SHA3512": hasher = sha3.New512() default: msg := "Invalid algorithm parameter passed go Checksum: %s" return checksum, fmt.Errorf(msg, algorithm) } hasher.Write(data) str := hex.EncodeToString(hasher.Sum(nil)) return str, nil }
/*Returns a sha512 hashed string*/ func Sha512(value string) string { hash := sha512.New() io.WriteString(hash, value) hashedString := hex.EncodeToString(hash.Sum(nil)) return hashedString }
// Verify returns true iff sig is a valid signature of message by publicKey. func Verify(publicKey *[PublicKeySize]byte, message []byte, sig *[SignatureSize]byte) bool { if sig[63]&224 != 0 { return false } var A edwards25519.ExtendedGroupElement if !A.FromBytes(publicKey) { return false } h := sha512.New() h.Write(sig[:32]) h.Write(publicKey[:]) h.Write(message) var digest [64]byte h.Sum(digest[:0]) var hReduced [32]byte edwards25519.ScReduce(&hReduced, &digest) var R edwards25519.ProjectiveGroupElement var b [32]byte copy(b[:], sig[32:]) edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &b) var checkR [32]byte R.ToBytes(&checkR) return subtle.ConstantTimeCompare(sig[:32], checkR[:]) == 1 }
// Sets the artifact fields func setArtifactData(artifact *Artifact, format string, symbols, libraries []string) error { // Format fields artifact.Format = format artifact.Symbols = symbols artifact.Imports = libraries // Read file for hashing fName := artifact.ArtifactDir file, err := ioutil.ReadFile(fName) if err != nil { return err } // Copies file to md5 hash array md5hasher := md5.New() md5hasher.Write(file) md5hash := md5hasher.Sum(nil) // Copies file to sha1 hash array sha1hasher := sha1.New() sha1hasher.Write(file) sha1hash := sha1hasher.Sum(nil) // Copies file to sha512 hash array sha512hasher := sha512.New() sha512hasher.Write(file) sha512hash := sha512hasher.Sum(nil) artifact.Md5 = fmt.Sprintf("%x", md5hash) artifact.Sha1 = fmt.Sprintf("%x", sha1hash) artifact.Sha512 = fmt.Sprintf("%x", sha512hash) return nil }
func (p *Profile) setMasterPassword(pwd string) error { var ( dk = pbkdf2.Key([]byte(pwd), p.Salt, p.Iterations, 64, sha512.New) derivedEncKey = dk[:32] derivedMacKey = dk[32:] ) masterKey, err := decrypt(nil, p.MasterKey, derivedEncKey, derivedMacKey) if err != nil { return err } overviewKey, err := decrypt(nil, p.OverviewKey, derivedEncKey, derivedMacKey) if err != nil { return err } mac := sha512.New() mac.Write(masterKey) macData := mac.Sum(nil) p.masterEncKey = macData[:32] p.masterMacKey = macData[32:] mac.Reset() mac.Write(overviewKey) macData = mac.Sum(nil) p.overviewEncKey = macData[:32] p.overviewMacKey = macData[32:] return nil }
// Decrypt walks over the tree and decrypts all values with the provided cipher, except those whose key ends with the UnencryptedSuffix specified on the Metadata struct. If decryption is successful, it returns the MAC for the decrypted tree. func (tree Tree) Decrypt(key []byte, cipher DataKeyCipher) (string, error) { hash := sha512.New() _, err := tree.Branch.walkBranch(tree.Branch, make([]string, 0), func(in interface{}, path []string) (interface{}, error) { var v interface{} if !strings.HasSuffix(path[len(path)-1], tree.Metadata.UnencryptedSuffix) { var err error v, err = cipher.Decrypt(in.(string), key, []byte(strings.Join(path, ":")+":")) if err != nil { return nil, fmt.Errorf("Could not decrypt value: %s", err) } } else { v = in } bytes, err := ToBytes(v) if err != nil { return nil, fmt.Errorf("Could not convert %s to bytes: %s", in, err) } hash.Write(bytes) return v, err }) if err != nil { return "", fmt.Errorf("Error walking tree: %s", err) } return fmt.Sprintf("%X", hash.Sum(nil)), nil }
func getHashSHA2(bitsize int) (hash.Hash, error) { switch bitsize { case 224: return sha256.New224(), nil case 256: return sha256.New(), nil case 384: return sha512.New384(), nil case 512: return sha512.New(), nil case 521: return sha512.New(), nil default: return nil, fmt.Errorf("Invalid bitsize. It was [%d]. Expected [224, 256, 384, 512, 521]", bitsize) } }
func process_file(filename string, complete chan Sumlist) { sumlist := Sumlist{} sumlist.filename = filename // Open the file and bail if we fail infile, err := os.Open(filename) if err != nil { log.Printf("Unable to open %s: %s", filename, err) complete <- sumlist return } defer infile.Close() // Create the checksum objects if flag_crc32 { sumlist.sums = append(sumlist.sums, Checksum{"CRC32", crc32.New(crc32.IEEETable)}) } if flag_crc64 { sumlist.sums = append(sumlist.sums, Checksum{"CRC64", crc64.New(crc64.MakeTable(crc64.ISO))}) } if flag_sha224 { sumlist.sums = append(sumlist.sums, Checksum{"SHA224", sha256.New224()}) } if flag_sha256 { sumlist.sums = append(sumlist.sums, Checksum{"SHA256", sha256.New()}) } if flag_sha384 { sumlist.sums = append(sumlist.sums, Checksum{"SHA384", sha512.New384()}) } if flag_sha512 { sumlist.sums = append(sumlist.sums, Checksum{"SHA512", sha512.New()}) } // Create our file reader reader := bufio.NewReader(infile) // Start a buffer and loop to read the entire file buf := make([]byte, 4096) for { read_count, err := reader.Read(buf) // If we get an error that is not EOF, then we have a problem if err != nil && err != io.EOF { log.Printf("Unable to open %s: %s", filename, err) complete <- sumlist return } // If the returned size is zero, we're at the end of the file if read_count == 0 { break } // Add the buffer contents to the checksum calculation for _, sum := range sumlist.sums { sum.hashFunc.Write(buf[:read_count]) } } complete <- sumlist }