本文整理匯總了Golang中crypto/sha256.Sum256函數的典型用法代碼示例。如果您正苦於以下問題:Golang Sum256函數的具體用法?Golang Sum256怎麽用?Golang Sum256使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Sum256函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: CreateActivityWithInfo
// 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
}
}
示例2: main
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
}
示例3: buildMasterKey
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
}
示例4: main
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))
}
}
示例5: Shad
// 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
}
示例6: main
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
}
示例7: main
func main() {
hash1 := sha256.Sum256([]byte("hello world"))
hash2 := sha256.Sum256([]byte("hello worlD"))
printHash(hash1)
printHash(hash2)
fmt.Println(diffBits(hash1, hash2))
}
示例8: NewHostedProgram
// 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
}
示例9: GetAddress
//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
}
示例10: CalcRootHash
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[:]))
}
示例11: AddFromRequest
// 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
}
示例12: encodeBase58Check
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
}
示例13: CountSha
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)
}
示例14: main
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))
}
示例15: NewHostedProgram
// 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
}