本文整理汇总了Golang中crypto/sha1.Sum函数的典型用法代码示例。如果您正苦于以下问题:Golang Sum函数的具体用法?Golang Sum怎么用?Golang Sum使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Sum函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: create
// 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)
}
示例2: ProcessAccountOverviewPassword
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"})
}
示例3: calculateDHSessionKeys
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
}
示例4: KeyVerify
// 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
}
示例5: scramble
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
}
示例6: calculateDHSessionKeys
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
}
示例7: QuoteVerify
// 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
}
示例8: SaltedHash
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)[:]))
}
示例9: HashedAndSalt
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[:]))
}
示例10: Put
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
}
示例11: getShare
//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")
}
示例12: Unsign
// 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
}
示例13: TestCachedFileStoreRead
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()
}
}
示例14: constantTimeEquals
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
}
示例15: createPing
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()
}