作者:jashpe
项目:bitmask-g
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
}
作者:sporkmonge
项目:bitmessage-g
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
}
作者:yrash
项目:mini
// 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()
}
}
作者:tcnks
项目:go-crypt
// (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)
}
作者:ActiveStat
项目:dn
// 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 ""
}
作者:FlyWing
项目:kubernete
// 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")
}
作者:sbhackerspac
项目:sbhx-snippet
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())
}
}
作者:imjorg
项目:flyn
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
}
作者:postfi
项目:libblockif
// 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
}
作者:DaveDaCod
项目:docke
// 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
}
作者:mark-adam
项目:clien
func computeDetachedDigest(nonce []byte, plaintext []byte) []byte {
hasher := sha512.New()
hasher.Write(nonce)
hasher.Write(plaintext)
return detachedDigest(hasher.Sum(nil))
}
作者:leepr
项目:gopla
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!")
}
作者:ancientlor
项目:hashsr
func (e *Engine) sha512() error {
data, err := computeHash(sha512.New(), e.stack.Pop())
if err == nil {
e.stack.Push(data)
}
return err
}
作者:SUNE
项目:polle
// 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)
}
作者:hecr
项目:
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()
}
}
作者:hecr
项目:
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, ","))
}
}
}
作者:coderhaoxi
项目:rk
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
}
作者:GehirnIn
项目:dhka
// 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()
}
}
}
作者:fdegui1
项目:difna
// 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
}
作者:devic
项目:flyn
// 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
}