コード例 #1
0
ファイル: kmgEncryptV2.go プロジェクト: keysonZZZ/kmg
/*
对称解密,
	不会修改输入的数据
*/
func DecryptV2(key []byte, data []byte) (output []byte, err error) {
	if len(data) < 16+64 {
		return nil, errors.New("[kmgCipher.Decrypt] input data too small")
	}
	keyHash := sha512.Sum512(key)
	aseKey := keyHash[:32]
	cbcIv := data[:16]
	block, err := aes.NewCipher(aseKey)
	if err != nil {
		return nil, err
	}
	if len(data)%block.BlockSize() != 0 {
		return nil, errors.New("[kmgCipher.Decrypt] input not full blocks")
	}
	output = make([]byte, len(data)-16)
	blockmode := cipher.NewCBCDecrypter(block, cbcIv)
	blockmode.CryptBlocks(output, data[16:])
	paddingSize := int(output[len(output)-1])
	if paddingSize > block.BlockSize() {
		return nil, errors.New("[kmgCipher.Decrypt] paddingSize out of range")
	}
	beforeCbcSize := len(data) - paddingSize - 64 - 16
	hashData := sha512.Sum512(output[:beforeCbcSize])
	if !bytes.Equal(hashData[:], output[beforeCbcSize:beforeCbcSize+64]) {
		return nil, errors.New("[kmgCipher.Decrypt] hash not match")
	}
	return output[:beforeCbcSize], nil
}
コード例 #2
0
ファイル: message.go プロジェクト: mastercactapus/bitmessage
func CalcVector(p []byte) InvVector {
	sum := sha512.Sum512(p)
	sum = sha512.Sum512(sum[:])
	var v InvVector
	copy(v[:], sum[:32])
	return v
}
コード例 #3
0
ファイル: user.go プロジェクト: kesyn/kanban
// EncodePasswd encodes password to safe format.
func (u *User) EncodePasswd() {
	hash := []byte(u.Passwd)
	dig := sha512.Sum512(hash)
	for i := 1; i < 5000; i++ {
		dig = sha512.Sum512(append(dig[:], hash[:]...))
	}
	newPasswd := base64.StdEncoding.EncodeToString(dig[:])
	u.Passwd = fmt.Sprintf("%s", newPasswd)
}
コード例 #4
0
ファイル: dice.go プロジェクト: intusco/fair
// VerifyRoll verifies an Intus.co roll is fair.
func VerifyRoll(r *Roll) error {
	serverHash, err := hex.DecodeString(r.ServerHash)
	if err != nil {
		return err
	}

	serverRand, err := hex.DecodeString(r.ServerRand)
	if err != nil {
		return err
	}

	// Does serverRand hash match?
	calcServerHash := sha512.Sum512(serverRand)
	if !bytes.Equal(calcServerHash[:], serverHash) {
		return errors.New("serverRand does not match serverHash")
	}
	log.Println("server hashes match")

	// Calculate roll value matches.
	clientRand, err := hex.DecodeString(r.ClientRand)
	if err != nil {
		return err
	}

	// Concatenate serverRand and clientRand.
	combRand := append(serverRand, clientRand...)

	// Hash the result.
	combHash := sha512.Sum512(combRand)

	// Determine the integer value of combHash.
	combValue := new(big.Int).SetBytes(combHash[:])

	// Now mod the winValue and value to get the provably fair rollValue that is
	// of range of [0, r.WinValue).
	rollValue := new(big.Int)
	new(big.Int).DivMod(combValue, big.NewInt(r.WinValue), rollValue)

	// Check roll values match.
	if rollValue.Int64() != r.RollValue {
		return errors.New("roll values do not match")
	}

	log.Printf("roll value calculated at %v", rollValue)

	// Now see if the roll was a winning one.
	if rollValue.Int64() < r.BetValue {
		log.Printf("provably fair win of %v Satoshi", r.WinValue)
	} else {
		log.Printf("provably fair loss of %v Satoshi", r.BetValue)
	}
	return nil
}
コード例 #5
0
ファイル: sha.go プロジェクト: Odd-Tablet/GoPL-exercises
func shaHash(fl string, a string) {
	if fl == "t" {
		fmt.Print("SHA384 Hash Value:\n")
		fmt.Printf("%x\n", sha512.Sum512([]byte(a)))
	} else if fl == "f" {
		fmt.Print("SHA512 Hash Value:\n")
		fmt.Printf("%x\n", sha512.Sum512([]byte(a)))
	} else {
		fmt.Print("SHA256 Hash Value:\n")
		fmt.Printf("%x\n", sha256.Sum256([]byte(a)))
	}
}
コード例 #6
0
// SHA512 sum for the given password.  If a SaltConf
// pointer is given as a parameter a salt with the given
// length will be returned with it included in the hash.
func (p *Password) SHA512(saltConf ...*SaltConf) ([64]byte, []byte) {
	if len(saltConf) > 0 {
		var saltLength int

		for _, i := range saltConf[0:] {
			saltLength = i.Length
		}

		salt := getRandomBytes(saltLength)
		return sha512.Sum512([]byte(fmt.Sprintf("%s%x", p.Pass, salt))), salt
	}
	return sha512.Sum512([]byte(p.Pass)), nil
}
コード例 #7
0
ファイル: main.go プロジェクト: aviflax/simplebench
func handle(w http.ResponseWriter, r *http.Request) {
	currentTime := time.Now().Unix()
	res := response{
		Time:     currentTime,
		Hash:     fmt.Sprintf("%x", sha512.Sum512([]byte(trueRemoteAddr(r)))),
		ClientIP: trueRemoteAddr(r),
	}
	resj, _ := json.Marshal(res)
	etag := fmt.Sprintf("\"%x\"", sha512.Sum512(resj))
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Etag", etag)
	w.Write(resj)
}
コード例 #8
0
ファイル: main.go プロジェクト: sonedazaurus/golang-training
func main() {
	usage := "Usage: echo -n hello | ./ex02 [256|384|512]"
	bytes, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	n := 256
	if len(os.Args) == 2 {
		n, _ = strconv.Atoi(os.Args[1])
	}

	switch n {
	case 256:
		fmt.Printf("%x\n", sha256.Sum256(bytes))
		os.Exit(0)
		return
	case 384:
		fmt.Printf("%x\n", sha512.Sum384(bytes))
		os.Exit(0)
		return
	case 512:
		fmt.Printf("%x\n", sha512.Sum512(bytes))
		os.Exit(0)
		return
	default:
		fmt.Println(usage)
		os.Exit(1)
		return
	}
}
コード例 #9
0
ファイル: veth.go プロジェクト: balagopalraj/clearlinux
func cmdAdd(args *skel.CmdArgs) error {
	conf := NetConf{}
	if err := json.Unmarshal(args.StdinData, &conf); err != nil {
		return fmt.Errorf("failed to load netconf: %v", err)
	}

	// run the IPAM plugin and get back the config to apply
	result, err := plugin.ExecAdd(conf.IPAM.Type, args.StdinData)
	if err != nil {
		return err
	}
	if result.IP4 == nil {
		return errors.New("IPAM plugin returned missing IPv4 config")
	}

	hostVethName, err := setupContainerVeth(args.Netns, args.IfName, conf.MTU, result)
	if err != nil {
		return err
	}

	if err = setupHostVeth(hostVethName, result.IP4); err != nil {
		return err
	}

	if conf.IPMasq {
		h := sha512.Sum512([]byte(args.Netns))
		chain := fmt.Sprintf("CNI-%s-%x", conf.Name, h[:8])
		if err = ip.SetupIPMasq(&result.IP4.IP, chain); err != nil {
			return err
		}
	}

	return plugin.PrintResult(result)
}
コード例 #10
0
ファイル: main.go プロジェクト: tscholl2/beacon
func init() {
	var filename string
	var err error
	flag.StringVar(&filename, "file", "key.txt",
		"file containing secret key")
	flag.Parse()
	f, err := ioutil.ReadFile(filename)
	if err != nil {
		panic(err)
	}
	b := sha512.Sum512(f)
	key, err = ecdsa.GenerateKey(elliptic.P256(), bytes.NewReader(b[:]))
	if err != nil {
		panic(err)
	}
	err = rs.Open("./test.db", key)
	if err != nil {
		panic(err)
	}
	m = new(mic.Reader)
	go func() {
		for {
			var bits [32]byte
			m.Read(bits[:])
			_, err := rs.New(bits)
			if err != nil {
				fmt.Printf("error making record %s\n", err)
			}
			time.Sleep(60 * time.Second)
		}
	}()
}
コード例 #11
0
ファイル: keys.go プロジェクト: carriercomm/repbin
// CalcSharedSecret does a triple DH from the keypacks to generate the shared secret. myKeys needs to contain private keys, peerKeys only needs public keys
// Sending determines if one is sender or recipient of a message.
func CalcSharedSecret(myKeys, peerKeys *KeyPack, nonce *[NonceSize]byte, sending bool) (sharedSecret [SharedKeySize]byte) {
	preKey := make([]byte, 3*Curve25519KeySize+NonceSize) // three keys plus nonce
	key1, key2, key3 := new(Curve25519Key), new(Curve25519Key), new(Curve25519Key)
	log.Secretf("TemporaryPrivKey: %x\n", *myKeys.TemporaryPrivKey)
	log.Secretf("ConstantPrivKey: %x\n", *myKeys.ConstantPrivKey)
	log.Secretf("TemporaryPubKey: %x\n", *peerKeys.TemporaryPubKey)
	log.Secretf("ConstantPubKey: %x\n", *peerKeys.ConstantPubKey)
	scalarMult(key1, myKeys.TemporaryPrivKey, peerKeys.TemporaryPubKey)
	log.Secretf("Key1: %x\n", *key1)
	scalarMult(key2, myKeys.ConstantPrivKey, peerKeys.TemporaryPubKey)
	scalarMult(key3, myKeys.TemporaryPrivKey, peerKeys.ConstantPubKey)
	preKey = append(preKey, key1[:]...)
	if sending {
		log.Secretf("Key2: %x\n", *key2)
		log.Secretf("Key3: %x\n", *key3)
		preKey = append(preKey, key2[:]...)
		preKey = append(preKey, key3[:]...)
	} else { // Swap for receiver
		log.Secretf("Key2: %x\n", *key3)
		log.Secretf("Key3: %x\n", *key2)
		preKey = append(preKey, key3[:]...)
		preKey = append(preKey, key2[:]...)

	}
	log.Secretf("Nonce: %x\n", *nonce)
	preKey = append(preKey, nonce[:]...)
	return sha512.Sum512(preKey)
}
コード例 #12
0
ファイル: passwordadmin.go プロジェクト: wulinxu/KeyAdmin-go
func _passpharseHash(passpharse []byte, encodingWay []string) (encodedpasspharse []byte) {
	encodepasspharse := passpharse
	for _, hashalgor := range encodingWay {
		switch hashalgor {
		case "md5":
			sum := md5.Sum(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha1":
			sum := sha1.Sum(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha224":
			sum := sha256.Sum224(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha256":
			sum := sha256.Sum256(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha384":
			sum := sha512.Sum384(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha512":
			sum := sha512.Sum512(encodepasspharse)
			encodepasspharse = sum[:]
		}
	}
	//issue if return with not args,the return value will be null
	return encodepasspharse
}
コード例 #13
0
ファイル: util.go プロジェクト: klizhentas/acbuild
// Hash takes an array of strings and returns their hash.
func Hash(strings ...string) (string, error) {
	var bytes []byte
	for _, s := range strings {
		bytes = append(bytes, []byte(s)...)
	}
	return fmt.Sprintf("%s%x", "sha512-", sha512.Sum512(bytes)), nil
}
コード例 #14
0
ファイル: attachment.go プロジェクト: 4cdn/srndv2
func createAttachment(content_type, fname string, body io.Reader) NNTPAttachment {

	media_type, _, err := mime.ParseMediaType(content_type)
	if err == nil {
		a := nntpAttachment{}
		_, err = io.Copy(&a.body, body)
		if err == nil {
			a.header = make(textproto.MIMEHeader)
			a.mime = media_type + "; charset=UTF-8"
			idx := strings.LastIndex(fname, ".")
			a.ext = ".txt"
			if idx > 0 {
				a.ext = fname[idx:]
			}
			a.header.Set("Content-Disposition", `form-data; filename="`+fname+`"; name="attachment"`)
			a.header.Set("Content-Type", a.mime)
			a.header.Set("Content-Transfer-Encoding", "base64")
			h := sha512.Sum512(a.body.Bytes())
			hashstr := base32.StdEncoding.EncodeToString(h[:])
			a.hash = h[:]
			a.filepath = hashstr + a.ext
			a.filename = fname
			return a
		}
	}
	return nil
}
コード例 #15
0
ファイル: ptp.go プロジェクト: sinfomicien/rkt
func cmdDel(args *skel.CmdArgs) error {
	conf := NetConf{}
	if err := json.Unmarshal(args.StdinData, &conf); err != nil {
		return fmt.Errorf("failed to load netconf: %v", err)
	}

	var ipn *net.IPNet
	err := ns.WithNetNSPath(args.Netns, false, func(hostNS *os.File) error {
		var err error
		ipn, err = ip.DelLinkByNameAddr(args.IfName, netlink.FAMILY_V4)
		return err
	})
	if err != nil {
		return err
	}

	if conf.IPMasq {
		h := sha512.Sum512([]byte(args.ContainerID))
		chain := fmt.Sprintf("CNI-%s-%x", conf.Name, h[:8])
		if err = ip.TeardownIPMasq(ipn, chain); err != nil {
			return err
		}
	}

	return ipam.ExecDel(conf.IPAM.Type, args.StdinData)
}
コード例 #16
0
ファイル: decrypt.go プロジェクト: mark-adams/client
func (ds *decryptStream) processEncryptionBlock(bl *EncryptionBlock) ([]byte, error) {

	blockNum := encryptionBlockNumber(bl.seqno - 1)

	if err := blockNum.check(); err != nil {
		return nil, err
	}

	nonce := ds.nonce.ForPayloadBox(blockNum)
	ciphertext := bl.PayloadCiphertext
	hash := sha512.Sum512(ciphertext)

	hashBox := ds.tagKey.Box(nonce, hash[:])
	ourAuthenticator := hashBox[:secretbox.Overhead]

	if !hmac.Equal(ourAuthenticator, bl.HashAuthenticators[ds.position]) {
		return nil, ErrBadTag(bl.seqno)
	}

	plaintext, ok := secretbox.Open([]byte{}, ciphertext, (*[24]byte)(nonce), (*[32]byte)(ds.payloadKey))
	if !ok {
		return nil, ErrBadCiphertext(bl.seqno)
	}

	// The encoding of the empty buffer implies the EOF.  But otherwise, all mechanisms are the same.
	if len(plaintext) == 0 {
		return nil, nil
	}
	return plaintext, nil
}
コード例 #17
0
ファイル: user.go プロジェクト: YusukeKanazawa/iotsample
// FactoryMethod
func NewUser(userName UserKey, password string) *User {
	return &User{
		UserName: userName,
		Password: sha512.Sum512([]byte(password)),
		clients:  clientList{},
	}
}
コード例 #18
0
ファイル: multipart.go プロジェクト: bosky101/minio
// NewMultipartUpload - initiate a new multipart session
func (donut API) NewMultipartUpload(bucket, key, contentType string) (string, error) {
	donut.lock.Lock()
	defer donut.lock.Unlock()

	if !IsValidBucket(bucket) {
		return "", iodine.New(BucketNameInvalid{Bucket: bucket}, nil)
	}
	if !IsValidObjectName(key) {
		return "", iodine.New(ObjectNameInvalid{Object: key}, nil)
	}
	if !donut.storedBuckets.Exists(bucket) {
		return "", iodine.New(BucketNotFound{Bucket: bucket}, nil)
	}
	storedBucket := donut.storedBuckets.Get(bucket).(storedBucket)
	objectKey := bucket + "/" + key
	if _, ok := storedBucket.objectMetadata[objectKey]; ok == true {
		return "", iodine.New(ObjectExists{Object: key}, nil)
	}
	id := []byte(strconv.FormatInt(rand.Int63(), 10) + bucket + key + time.Now().String())
	uploadIDSum := sha512.Sum512(id)
	uploadID := base64.URLEncoding.EncodeToString(uploadIDSum[:])[:47]

	storedBucket.multiPartSession[key] = MultiPartSession{
		uploadID:   uploadID,
		initiated:  time.Now(),
		totalParts: 0,
	}
	multiPartCache := data.NewCache(0)
	multiPartCache.OnEvicted = donut.evictedPart
	donut.multiPartObjects[uploadID] = multiPartCache
	donut.storedBuckets.Set(bucket, storedBucket)
	return uploadID, nil
}
コード例 #19
0
ファイル: ed25519.go プロジェクト: Rudloff/platform
// GenerateKey generates a public/private key pair using entropy from rand.
// If rand is nil, crypto/rand.Reader will be used.
func GenerateKey(rand io.Reader) (publicKey PublicKey, privateKey PrivateKey, err error) {
	if rand == nil {
		rand = cryptorand.Reader
	}

	privateKey = make([]byte, PrivateKeySize)
	publicKey = make([]byte, PublicKeySize)
	_, err = io.ReadFull(rand, privateKey[:32])
	if err != nil {
		return nil, nil, err
	}

	digest := sha512.Sum512(privateKey[:32])
	digest[0] &= 248
	digest[31] &= 127
	digest[31] |= 64

	var A edwards25519.ExtendedGroupElement
	var hBytes [32]byte
	copy(hBytes[:], digest[:])
	edwards25519.GeScalarMultBase(&A, &hBytes)
	var publicKeyBytes [32]byte
	A.ToBytes(&publicKeyBytes)

	copy(privateKey[32:], publicKeyBytes[:])
	copy(publicKey, publicKeyBytes[:])

	return publicKey, privateKey, nil
}
コード例 #20
0
ファイル: store.go プロジェクト: husio/jinx
// Valid return true if given password is valid user password.
func (p PasswordField) Valid(password string) bool {
	salt := p.Salt()
	raw := sha512.Sum512([]byte(salt + password))
	hash := base64.StdEncoding.EncodeToString(raw[:])
	passHash := fmt.Sprintf("%s$$%s", salt, hash)
	return passHash == p.String()
}
コード例 #21
0
ファイル: types.go プロジェクト: mbentley/notary
// CheckHashes verifies all the checksums specified by the "hashes" of the payload.
func CheckHashes(payload []byte, name string, hashes Hashes) error {
	cnt := 0

	// k, v indicate the hash algorithm and the corresponding value
	for k, v := range hashes {
		switch k {
		case notary.SHA256:
			checksum := sha256.Sum256(payload)
			if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
				return ErrMismatchedChecksum{alg: notary.SHA256, name: name, expected: hex.EncodeToString(v)}
			}
			cnt++
		case notary.SHA512:
			checksum := sha512.Sum512(payload)
			if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
				return ErrMismatchedChecksum{alg: notary.SHA512, name: name, expected: hex.EncodeToString(v)}
			}
			cnt++
		}
	}

	if cnt == 0 {
		return ErrMissingMeta{Role: name}
	}

	return nil
}
コード例 #22
0
ファイル: main.go プロジェクト: plumbum/go-samples
func main() {

	dat, err := ioutil.ReadFile(os.Args[0])
	check(err)

	// Calculate sums
	s256 := sha256.Sum256(dat)
	s512 := sha512.Sum512(dat)

	// Calculate multihash
	h, err := multihash.Encode(s256[:], multihash.SHA2_256)
	check(err)
	multiSha256 := b58.Encode(h)

	fmt.Println("Multihash256/58: ", len(multiSha256), string(multiSha256))

	// Base 58 encoding
	s256b58 := b58.Encode(s256[:])
	s512b58 := b58.Encode(s512[:])

	// Base 64 encoding
	enc := base64.RawURLEncoding

	s256b64 := enc.EncodeToString(s256[:])
	s512b64 := enc.EncodeToString(s512[:])

	fmt.Println("SHA256/base58  : ", len(s256b58), string(s256b58))
	fmt.Println("SHA256/base64  : ", len(s256b64), string(s256b64))
	fmt.Println("SHA512/base58  : ", len(s512b58), string(s512b58))
	fmt.Println("SHA512/base64  : ", len(s512b64), string(s512b64))
}
コード例 #23
0
ファイル: kvm.go プロジェクト: vincentvdk/rkt
// teardownKvmNets teardown every active networking from networking by
// removing tuntap interface and releasing its ip from IPAM plugin
func (n *Networking) teardownKvmNets() {
	for _, an := range n.nets {
		switch an.conf.Type {
		case "ptp":
			// remove tuntap interface
			tuntap.RemovePersistentIface(an.runtime.IfName, tuntap.Tap)
			// remove masquerading if it was prepared
			if an.conf.IPMasq {
				h := sha512.Sum512([]byte(n.podID.String()))
				chain := fmt.Sprintf("CNI-%s-%x", an.conf.Name, h[:8])
				err := ip.TeardownIPMasq(&net.IPNet{
					IP:   an.runtime.IP,
					Mask: net.IPMask(an.runtime.Mask),
				}, chain)
				if err != nil {
					log.Printf("Error on removing masquerading: %q", err)
				}
			}
			// ugly hack again to directly call IPAM plugin to release IP
			an.conf.Type = an.conf.IPAM.Type

			_, err := n.execNetPlugin("DEL", &an, an.runtime.IfName)
			if err != nil {
				log.Printf("Error executing network plugin: %q", err)
			}
		default:
			log.Printf("Unsupported network type: %q", an.conf.Type)
		}
	}
}
コード例 #24
0
ファイル: message.go プロジェクト: mastercactapus/bitmessage
func (w *MessageWriter) WriteMessage(m Message) (int, error) {
	cmd := []byte(m.Command())
	if len(cmd) > 12 {
		return 0, ErrTooLong
	}
	data, err := m.MarshalBinary()
	if err != nil {
		return 0, err
	}
	b := make([]byte, 24)
	order.PutUint32(b, MessageMagic)
	copy(b[4:], cmd)
	order.PutUint32(b[16:], uint32(len(data)))
	sum := sha512.Sum512(data)
	copy(b[20:], sum[:4])
	n, err := w.Write(b)
	if err != nil {
		return n, err
	}
	n2, err := w.Write(data)
	if err != nil {
		return n + n2, err
	}
	return n + n2, nil
}
コード例 #25
0
ファイル: main.go プロジェクト: stmansour/phonebook
func createUser(v *personDetail) {
	v.RID = 1
	fillUserFields(v)

	sha := sha512.Sum512([]byte("accord"))
	passhash := fmt.Sprintf("%x", sha)

	stmt, err := App.db.Prepare("INSERT INTO people (UserName,passhash,FirstName,LastName,RID,Status," + //6
		"OfficePhone,CellPhone,OfficeFax," + //9
		"HomeStreetAddress,HomeCity,HomeState,HomePostalCode,HomeCountry," + // 14
		"DeptCode,JobCode,PreferredName,EmergencyContactName,EmergencyContactPhone," + // 19
		"PrimaryEmail,SecondaryEmail,ClassCode,CoCode) " + // 23
		//       1                 10                  20
		" VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
	if nil != err {
		fmt.Printf("error = %v\n", err)
		os.Exit(1)
	}
	_, err = stmt.Exec(v.UserName, passhash, v.FirstName, v.LastName, v.RID, v.Status,
		v.OfficePhone, v.CellPhone, v.OfficeFax,
		v.HomeStreetAddress, v.HomeCity, v.HomeState, v.HomePostalCode, v.HomeCountry,
		v.DeptCode, v.JobCode, v.PreferredName, v.EmergencyContactName, v.EmergencyContactPhone,
		v.PrimaryEmail, v.SecondaryEmail, v.ClassCode, v.CoCode)
	if nil != err {
		fmt.Printf("error = %v\n", err)
	}
	v.Pro = &Tester
	//fmt.Printf("Added user to database %s:  username: %s, access role: %d\n", App.DBName, v.UserName, v.RID)

}
コード例 #26
0
ファイル: encrypt.go プロジェクト: mark-adams/client
func (es *encryptStream) encryptBytes(b []byte) error {

	if err := es.numBlocks.check(); err != nil {
		return err
	}

	nonce := es.nonce.ForPayloadBox(es.numBlocks)
	ciphertext := secretbox.Seal([]byte{}, b, (*[24]byte)(nonce), (*[32]byte)(&es.payloadKey))
	hash := sha512.Sum512(ciphertext)

	block := EncryptionBlock{
		PayloadCiphertext: ciphertext,
	}

	for _, tagKey := range es.tagKeys {
		hashBox := tagKey.Box(nonce, hash[:])
		authenticator := hashBox[:secretbox.Overhead]
		block.HashAuthenticators = append(block.HashAuthenticators, authenticator)
	}

	if err := es.encoder.Encode(block); err != nil {
		return err
	}

	es.numBlocks++
	return nil
}
コード例 #27
0
ファイル: common.go プロジェクト: jgrahamc/h2scan
// ticketKeyFromBytes converts from the external representation of a session
// ticket key to a ticketKey. Externally, session ticket keys are 32 random
// bytes and this function expands that into sufficient name and key material.
func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
	hashed := sha512.Sum512(b[:])
	copy(key.keyName[:], hashed[:ticketKeyNameLen])
	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
	return key
}
コード例 #28
0
ファイル: types.go プロジェクト: beerbubble/docker
// CheckHashes verifies all the checksums specified by the "hashes" of the payload.
func CheckHashes(payload []byte, hashes Hashes) error {
	cnt := 0

	// k, v indicate the hash algorithm and the corresponding value
	for k, v := range hashes {
		switch k {
		case notary.SHA256:
			checksum := sha256.Sum256(payload)
			if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
				return ErrMismatchedChecksum{alg: notary.SHA256}
			}
			cnt++
		case notary.SHA512:
			checksum := sha512.Sum512(payload)
			if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
				return ErrMismatchedChecksum{alg: notary.SHA512}
			}
			cnt++
		}
	}

	if cnt == 0 {
		return fmt.Errorf("at least one supported hash needed")
	}

	return nil
}
コード例 #29
0
ファイル: sql_store.go プロジェクト: alphafeng/platform
func encrypt(key []byte, text string) (string, error) {

	if text == "" || text == "{}" {
		return "", nil
	}

	plaintext := []byte(text)
	skey := sha512.Sum512(key)
	ekey, akey := skey[:32], skey[32:]

	block, err := aes.NewCipher(ekey)
	if err != nil {
		return "", err
	}

	macfn := hmac.New(sha256.New, akey)
	ciphertext := make([]byte, aes.BlockSize+macfn.Size()+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(crand.Reader, iv); err != nil {
		return "", err
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize+macfn.Size():], plaintext)
	macfn.Write(ciphertext[aes.BlockSize+macfn.Size():])
	mac := macfn.Sum(nil)
	copy(ciphertext[aes.BlockSize:aes.BlockSize+macfn.Size()], mac)

	return base64.URLEncoding.EncodeToString(ciphertext), nil
}
コード例 #30
0
ファイル: message.go プロジェクト: kyonetca/emp
// Encrypt plainText into an Encrypted Published Message using the given private key.
func EncryptPub(log chan string, src_privkey []byte, plainText string) *EncryptedMessage {
	// Generate New Public/Private Key Pair
	D1, X1, Y1 := CreateKey(log)

	// Point Multiply to get new Pubkey
	PubX, PubY := elliptic.P256().ScalarMult(X1, Y1, src_privkey)

	// Generate Pubkey hashes
	PubHash := sha512.Sum512(elliptic.Marshal(elliptic.P256(), PubX, PubY))
	PubHash_E := PubHash[:32]
	PubHash_M := PubHash[32:64]

	IV, cipherText, _ := SymmetricEncrypt(PubHash_E, plainText)

	// Generate HMAC
	mac := hmac.New(sha256.New, PubHash_M)
	mac.Write(cipherText)
	HMAC := mac.Sum(nil)

	ret := new(EncryptedMessage)
	copy(ret.IV[:], IV[:])
	copy(ret.PublicKey[:32], D1)
	ret.CipherText = cipherText
	copy(ret.HMAC[:], HMAC)

	return ret
}