本文整理汇总了Golang中golang.org/x/crypto/sha3.ShakeSum256函数的典型用法代码示例。如果您正苦于以下问题:Golang ShakeSum256函数的具体用法?Golang ShakeSum256怎么用?Golang ShakeSum256使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ShakeSum256函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: ShareMask
func (s *Server) ShareMask(clientDH *ClientDH, serverPub *[]byte) error {
pub, shared := s.shareSecret(UnmarshalPoint(s.suite, clientDH.Public))
mask := MarshalPoint(shared)
for r := 0; r < MaxRounds; r++ {
if r == 0 {
sha3.ShakeSum256(s.maskss[r][clientDH.Id], mask)
} else {
sha3.ShakeSum256(s.maskss[r][clientDH.Id], s.maskss[r-1][clientDH.Id])
}
}
*serverPub = MarshalPoint(pub)
return nil
}
开发者ID:Xyroe,项目名称:riffle,代码行数:13,代码来源:server.go
示例2: ShareSecret
func (s *Server) ShareSecret(clientDH *ClientDH, serverPub *[]byte) error {
pub, shared := s.shareSecret(UnmarshalPoint(s.suite, clientDH.Public))
secret := MarshalPoint(shared)
for r := 0; r < MaxRounds; r++ {
if r == 0 {
sha3.ShakeSum256(s.secretss[r][clientDH.Id], secret)
} else {
sha3.ShakeSum256(s.secretss[r][clientDH.Id], s.secretss[r-1][clientDH.Id])
}
}
//s.secretss[clientDH.Id] = make([]byte, len(MarshalPoint(shared)))
*serverPub = MarshalPoint(pub)
return nil
}
开发者ID:Xyroe,项目名称:riffle,代码行数:14,代码来源:server.go
示例3: CheckCommitment
func CheckCommitment(commitment []byte, profile *proto.EncodedProfile) bool {
// The hash used here is modeled as a random oracle. This means that SHA3
// is fine but SHA2 is not (consider HMAC-SHA2 instead).
var commitmentCheck [64]byte
sha3.ShakeSum256(commitmentCheck[:], profile.Encoding) // the profile includes a nonce
return bytes.Equal(commitment[:], commitmentCheck[:])
}
开发者ID:postfix,项目名称:coname,代码行数:7,代码来源:lookup.go
示例4: ServeIzkp
// ServeIzkp returns an http.Handler that reads an input file and
// computes an interactive zero-knowledge proof-of-posession protocol.
// (This is completely unused, but isn't it cool?)
func ServeIzkp(fn string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadFile(fn)
if err != nil {
glog.Errorf("error reading file %s: %s", fn, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
chalString := r.Header.Get("x-izkp-challenge")
if chalString == "" {
glog.Infof("didn't receive a challenge, so using a raw hash")
d := make([]byte, 64)
sha3.ShakeSum256(d, b)
w.Write(d)
return
}
challenge := []byte(chalString)
glog.Infof("received a challenge of length %d", len(challenge))
h := sha3.New512()
h.Write(challenge)
h.Write(b)
d := make([]byte, 64)
h.Sum(d)
w.Write(d)
return
}
}
开发者ID:postfix,项目名称:keyshop,代码行数:30,代码来源:main.go
示例5: GetResponse
/////////////////////////////////
//Download
////////////////////////////////
func (s *Server) GetResponse(cmask ClientMask, response *[]byte) error {
t := time.Now()
round := cmask.Round % MaxRounds
otherBlocks := make([][]byte, len(s.servers))
var wg sync.WaitGroup
for i := range otherBlocks {
if i == s.id {
otherBlocks[i] = make([]byte, BlockSize)
} else {
wg.Add(1)
go func(i int, cmask ClientMask) {
defer wg.Done()
curBlock := <-s.rounds[round].xorsChan[i][cmask.Id]
otherBlocks[i] = curBlock.Block
}(i, cmask)
}
}
wg.Wait()
<-s.rounds[round].blocksRdy[cmask.Id]
if cmask.Id == 0 && profile {
fmt.Println(cmask.Id, "down_network:", time.Since(t))
}
r := ComputeResponse(s.rounds[round].allBlocks, cmask.Mask, s.secretss[round][cmask.Id])
sha3.ShakeSum256(s.secretss[round][cmask.Id], s.secretss[round][cmask.Id])
Xor(Xors(otherBlocks), r)
*response = r
return nil
}
开发者ID:Xyroe,项目名称:riffle,代码行数:31,代码来源:server.go
示例6: ShakeSum256
func ShakeSum256(password string) []byte {
buf := []byte(password)
// A hash needs to be 64 bytes long to have 256-bit collision resistance.
h := make([]byte, 64)
// Compute a 64-byte hash of buf and put it in h.
sha3.ShakeSum256(h, buf)
return h
}
开发者ID:meshwalker,项目名称:libcrypto2go,代码行数:8,代码来源:libCrypto2Go.go
示例7: NewSHA3Shake256
func NewSHA3Shake256(payloadLen int) func() {
input := NewRand(payloadLen)
var hash = make([]byte, 64)
return func() {
sha3.ShakeSum256(hash, input)
}
}
开发者ID:ecb,项目名称:rtt-go,代码行数:8,代码来源:main.go
示例8: hashToCurve
func hashToCurve(m []byte) *edwards25519.ExtendedGroupElement {
// H(n) = (f(h(n))^8)
var hmb [32]byte
sha3.ShakeSum256(hmb[:], m)
var hm edwards25519.ExtendedGroupElement
extra25519.HashToEdwards(&hm, &hmb)
edwards25519.GeDouble(&hm, &hm)
edwards25519.GeDouble(&hm, &hm)
edwards25519.GeDouble(&hm, &hm)
return &hm
}
开发者ID:Liamsi,项目名称:coname,代码行数:11,代码来源:vrf.go
示例9: SelectChallenges
//TODO: need to select based on some pseudorandomness/gamma function?
// Note that these challenges are different from those of cryptocurrency
func (v *Verifier) SelectChallenges(seed []byte) []int64 {
challenges := make([]int64, v.beta*int(v.log2))
rands := make([]byte, v.beta*int(v.log2)*8)
sha3.ShakeSum256(rands, seed) //PRNG
for i := range challenges {
val, num := binary.Uvarint(rands[i*8 : (i+1)*8])
if num < 0 {
panic("Couldn't read PRNG")
}
challenges[i] = int64(val % uint64(v.size))
}
return challenges
}
开发者ID:kwonalbert,项目名称:spacemint,代码行数:15,代码来源:verifier.go
示例10: DownloadSlot
func (c *Client) DownloadSlot(slot int, rnd uint64) []byte {
//all but one server uses the prng technique
round := rnd % MaxRounds
maskSize := len(c.maskss[round][0])
finalMask := make([]byte, maskSize)
SetBit(slot, true, finalMask)
mask := Xors(c.maskss[round])
Xor(c.maskss[round][c.myServer], mask)
Xor(finalMask, mask)
//one response includes all the secrets
response := make([]byte, BlockSize)
secretsXor := Xors(c.secretss[round])
cMask := ClientMask{Mask: mask, Id: c.id, Round: rnd}
t := time.Now()
err := c.rpcServers[c.myServer].Call("Server.GetResponse", cMask, &response)
if err != nil {
log.Fatal("Could not get response: ", err)
}
if c.id == 0 && profile {
fmt.Println(c.id, "down_network_total:", time.Since(t))
}
Xor(secretsXor, response)
for i := range c.secretss[round] {
sha3.ShakeSum256(c.secretss[round][i], c.secretss[round][i])
}
for i := range c.maskss[round] {
sha3.ShakeSum256(c.maskss[round][i], c.maskss[round][i])
}
return response
}
开发者ID:Xyroe,项目名称:riffle,代码行数:37,代码来源:client.go
示例11: TestKeyserverRejectsMissignedUpdate
func TestKeyserverRejectsMissignedUpdate(t *testing.T) {
dieOnCtrlC()
kss, caPool, clks, _, ck, clientConfig, teardown := setupRealm(t, 3, 3)
defer teardown()
stop := stoppableSyncedClocks(clks)
defer close(stop)
waitForFirstEpoch(kss[0], clientConfig.Realms[0].VerificationPolicy.GetQuorum())
clientTLS, err := clientConfig.Realms[0].ClientTLS.Config(ck)
if err != nil {
t.Fatal(err)
}
_, alicePk, aliceEntry, aliceProfile := doRegister(t, kss[0], clientConfig, clientTLS, caPool, clks[0].Now(), alice, 0, proto.Profile{
Nonce: []byte("noncenoncenonceNONCE"),
Keys: map[string][]byte{"abc": []byte{1, 2, 3}, "xyz": []byte("TEST 456")},
})
var aliceKeyIdBytes [8]byte
sha3.ShakeSum256(aliceKeyIdBytes[:], proto.MustMarshal(alicePk))
aliceKeyid := binary.BigEndian.Uint64(aliceKeyIdBytes[:8])
_, badSk, _ := ed25519.GenerateKey(rand.Reader)
conn, err := grpc.Dial(kss[1].publicListen.Addr().String(), grpc.WithTransportCredentials(credentials.NewTLS(clientTLS)))
if err != nil {
t.Fatal(err)
}
updateC := proto.NewE2EKSPublicClient(conn)
_, err = updateC.Update(context.Background(), &proto.UpdateRequest{
Update: &proto.SignedEntryUpdate{
NewEntry: *aliceEntry,
Signatures: map[uint64][]byte{aliceKeyid: ed25519.Sign(badSk, aliceEntry.Encoding)[:]},
},
Profile: *aliceProfile,
LookupParameters: &proto.LookupRequest{
UserId: alice,
QuorumRequirement: clientConfig.Realms[0].VerificationPolicy.GetQuorum(),
},
})
if err == nil {
t.Fatalf("update went through even though it was signed with the wrong key")
}
}
开发者ID:Liamsi,项目名称:coname,代码行数:43,代码来源:server_test.go
示例12: VerifyLookup
func VerifyLookup(cfg *proto.Config, user string, pf *proto.LookupProof, now time.Time) (keys map[string][]byte, err error) {
if pf.UserId != "" && pf.UserId != user {
return nil, fmt.Errorf("VerifyLookup: proof specifies different user ID: %q != %q", pf.UserId, user)
}
realm, err := GetRealmByUser(cfg, user)
if err != nil {
return nil, err
}
if !vrf.Verify(realm.VRFPublic, []byte(user), pf.Index, pf.IndexProof) {
return nil, fmt.Errorf("VerifyLookup: VRF verification failed")
}
root, err := VerifyConsensus(realm, pf.Ratifications, now)
if err != nil {
return
}
verifiedEntryHash, err := reconstructTreeAndLookup(realm.TreeNonce, root, pf.Index, pf.TreeProof)
if err != nil {
return nil, fmt.Errorf("VerifyLookup: failed to verify the lookup: %v", err)
}
if verifiedEntryHash == nil {
if pf.Entry != nil {
return nil, fmt.Errorf("VerifyLookup: non-empty entry %x did not match verified lookup result <nil>", pf.Entry)
}
if pf.Profile != nil {
return nil, fmt.Errorf("VerifyLookup: non-empty profile %x did not match verified lookup result <nil>", pf.Profile)
}
return nil, nil
} else {
var entryHash [32]byte
sha3.ShakeSum256(entryHash[:], pf.Entry.Encoding)
if !bytes.Equal(entryHash[:], verifiedEntryHash) {
return nil, fmt.Errorf("VerifyLookup: entry hash %x did not match verified lookup result %x", entryHash, verifiedEntryHash)
}
if !CheckCommitment(pf.Entry.ProfileCommitment, pf.Profile) {
return nil, fmt.Errorf("VerifyLookup: profile does not match the hash in the entry")
}
return pf.Profile.Keys, nil
}
}
开发者ID:postfix,项目名称:coname,代码行数:42,代码来源:lookup.go
示例13: verifyUpdateEdge
func (ks *Keyserver) verifyUpdateEdge(req *proto.UpdateRequest) error {
if len(req.Update.NewEntry.Index) != vrf.Size {
return fmt.Errorf("index '%x' has wrong length (expected %d)", req.Update.NewEntry.Index, vrf.Size)
}
prevUpdate, err := ks.getUpdate(req.Update.NewEntry.Index, math.MaxUint64)
if err != nil {
log.Print(err)
return fmt.Errorf("internal error")
}
if prevUpdate == nil { // registration: check email proof
if !ks.insecureSkipEmailProof {
email, payload, err := dkim.CheckEmailProof(req.DKIMProof, ks.emailProofToAddr,
ks.emailProofSubjectPrefix, ks.lookupTXT, ks.clk.Now)
if err != nil {
return fmt.Errorf("failed to verify DKIM proof: %s", err)
}
if got, want := email, req.LookupParameters.UserId; got != want {
return fmt.Errorf("requested user ID does not match the email proof: %q != %q", got, want)
}
lastAtIndex := strings.LastIndex(req.LookupParameters.UserId, "@")
if lastAtIndex == -1 {
return fmt.Errorf("requested user id is not a valid email address: %q", req.LookupParameters.UserId)
}
if _, ok := ks.emailProofAllowedDomains[req.LookupParameters.UserId[lastAtIndex+1:]]; !ok {
return fmt.Errorf("domain not in registration whitelist: %q", req.LookupParameters.UserId[lastAtIndex+1:])
}
entryHash, err := base64.StdEncoding.DecodeString(payload)
if err != nil {
return fmt.Errorf("bad base64 in email proof: %q", payload)
}
var entryHashProposed [32]byte
sha3.ShakeSum256(entryHashProposed[:], req.Update.NewEntry.Encoding)
if !bytes.Equal(entryHashProposed[:], entryHash[:]) {
return fmt.Errorf("email proof does not match requested entry: %s vs %s (%x)", base64.StdEncoding.EncodeToString(entryHashProposed[:]), payload, req.Update.NewEntry.Encoding)
}
}
}
return ks.verifyUpdateDeterministic(prevUpdate, req)
}
开发者ID:postfix,项目名称:coname,代码行数:40,代码来源:update.go
示例14: KeyID
// KeyID computes the ID of public key.
func KeyID(sv *PublicKey) uint64 {
var h [8]byte
sha3.ShakeSum256(h[:], MustMarshal(sv))
return binary.LittleEndian.Uint64(h[:8])
}
开发者ID:Liamsi,项目名称:coname,代码行数:6,代码来源:keyid.go
示例15: doUpdate
func doUpdate(
t *testing.T, ks *Keyserver, clientConfig *proto.Config, clientTLS *tls.Config, caPool *x509.CertPool, now time.Time,
name string, sk *[ed25519.PrivateKeySize]byte, pk *proto.PublicKey, version uint64, profileContents proto.Profile,
) (*proto.EncodedEntry, *proto.EncodedProfile) {
conn, err := grpc.Dial(ks.publicListen.Addr().String(), grpc.WithTransportCredentials(credentials.NewTLS(clientTLS)))
if err != nil {
t.Fatal(err)
}
publicC := proto.NewE2EKSPublicClient(conn)
// First, do a lookup to retrieve the index
lookup, err := publicC.Lookup(context.Background(), &proto.LookupRequest{
UserId: name,
// We don't care about any signatures here; the server just needs to tell us the index.
QuorumRequirement: &proto.QuorumExpr{
Threshold: 0,
Candidates: []uint64{},
Subexpressions: []*proto.QuorumExpr{},
},
})
if err != nil {
t.Fatal(err)
}
index := lookup.Index
// Do the update
var keyidBytes [8]byte
sha3.ShakeSum256(keyidBytes[:], proto.MustMarshal(pk))
keyid := binary.BigEndian.Uint64(keyidBytes[:8])
profile := proto.EncodedProfile{
Profile: profileContents,
}
profile.UpdateEncoding()
var commitment [64]byte
sha3.ShakeSum256(commitment[:], profile.Encoding)
entry := proto.EncodedEntry{
Entry: proto.Entry{
Index: index,
Version: version,
UpdatePolicy: &proto.AuthorizationPolicy{
PublicKeys: map[uint64]*proto.PublicKey{keyid: pk},
PolicyType: &proto.AuthorizationPolicy_Quorum{Quorum: &proto.QuorumExpr{
Threshold: 1,
Candidates: []uint64{keyid},
Subexpressions: []*proto.QuorumExpr{},
},
}},
ProfileCommitment: commitment[:],
},
}
entry.UpdateEncoding()
proof, err := publicC.Update(context.Background(), &proto.UpdateRequest{
Update: &proto.SignedEntryUpdate{
NewEntry: entry,
Signatures: map[uint64][]byte{keyid: ed25519.Sign(sk, entry.Encoding)[:]},
},
Profile: profile,
LookupParameters: &proto.LookupRequest{
UserId: name,
QuorumRequirement: clientConfig.Realms[0].VerificationPolicy.GetQuorum(),
},
})
if err != nil {
t.Fatal(err)
}
if got, want := proof.Profile.Encoding, profile.Encoding; !bytes.Equal(got, want) {
t.Errorf("updated profile didn't roundtrip: %x != %x", got, want)
}
_, err = coname.VerifyLookup(clientConfig, name, proof, now)
if err != nil {
t.Fatal(err)
}
return &entry, &profile
}
开发者ID:Liamsi,项目名称:coname,代码行数:75,代码来源:server_test.go
示例16: hash
func hash(clear string) string {
h := make([]byte, 64)
sha3.ShakeSum256(h, []byte(clear))
return fmt.Sprintf("%x", h)
}
开发者ID:konek,项目名称:auth-server,代码行数:6,代码来源:hash.go
示例17: step
// step is called by run and changes the in-memory state. No i/o allowed.
func (ks *Keyserver) step(step *proto.KeyserverStep, rs *proto.ReplicaState, wb kv.Batch) (deferredIO func()) {
// ks: &const
// step, rs, wb: &mut
switch step.Type.(type) {
case *proto.KeyserverStep_Update:
index := step.GetUpdate().Update.NewEntry.Index
prevUpdate, err := ks.getUpdate(index, math.MaxUint64)
if err != nil {
log.Printf("getUpdate: %s", err)
ks.wr.Notify(step.UID, updateOutput{Error: fmt.Errorf("internal error")})
return
}
if err := ks.verifyUpdateDeterministic(prevUpdate, step.GetUpdate()); err != nil {
ks.wr.Notify(step.UID, updateOutput{Error: err})
return
}
latestTree := ks.merkletree.GetSnapshot(rs.LatestTreeSnapshot)
// sanity check: compare previous version in Merkle tree vs in updates table
prevEntryHashTree, _, err := latestTree.Lookup(index)
if err != nil {
ks.wr.Notify(step.UID, updateOutput{Error: fmt.Errorf("internal error")})
return
}
var prevEntryHash []byte
if prevUpdate != nil {
prevEntryHash = make([]byte, 32)
sha3.ShakeSum256(prevEntryHash, prevUpdate.Update.NewEntry.Encoding)
}
if !bytes.Equal(prevEntryHashTree, prevEntryHash) {
log.Fatalf("ERROR: merkle tree and DB inconsistent for index %x: %x vs %x", index, prevEntryHashTree, prevEntryHash)
}
var entryHash [32]byte
sha3.ShakeSum256(entryHash[:], step.GetUpdate().Update.NewEntry.Encoding)
newTree, err := latestTree.BeginModification()
if err != nil {
ks.wr.Notify(step.UID, updateOutput{Error: fmt.Errorf("internal error")})
return
}
if err := newTree.Set(index, entryHash[:]); err != nil {
log.Printf("setting index '%x' gave error: %s", index, err)
ks.wr.Notify(step.UID, updateOutput{Error: fmt.Errorf("internal error")})
return
}
rs.LatestTreeSnapshot = newTree.Flush(wb).Nr
epochNr := rs.LastEpochDelimiter.EpochNumber + 1
wb.Put(tableUpdateRequests(index, epochNr), proto.MustMarshal(step.GetUpdate()))
ks.wr.Notify(step.UID, updateOutput{Epoch: epochNr})
rs.PendingUpdates = true
ks.updateEpochProposer()
if rs.LastEpochNeedsRatification {
// We need to wait for the last epoch to appear in the verifier log before
// inserting this update.
wb.Put(tableUpdatesPendingRatification(rs.NextIndexLog), proto.MustMarshal(step.GetUpdate().Update))
} else {
// We can deliver the update to verifiers right away.
return ks.verifierLogAppend(&proto.VerifierStep{Type: &proto.VerifierStep_Update{Update: step.GetUpdate().Update}}, rs, wb)
}
case *proto.KeyserverStep_EpochDelimiter:
if step.GetEpochDelimiter().EpochNumber <= rs.LastEpochDelimiter.EpochNumber {
return // a duplicate of this step has already been handled
}
rs.LastEpochDelimiter = *step.GetEpochDelimiter()
log.Printf("epoch %d", step.GetEpochDelimiter().EpochNumber)
rs.PendingUpdates = false
ks.resetEpochTimers(rs.LastEpochDelimiter.Timestamp.Time())
// rs.ThisReplicaNeedsToSignLastEpoch might already be true, if a majority
// signed that did not include us. This will make us skip signing the last
// epoch, but that's fine.
rs.ThisReplicaNeedsToSignLastEpoch = true
// However, it's not okay to see a new epoch delimiter before the previous
// epoch has been ratified.
if rs.LastEpochNeedsRatification {
log.Panicf("new epoch delimiter but last epoch not ratified")
}
rs.LastEpochNeedsRatification = true
ks.updateEpochProposer()
deferredIO = ks.updateSignatureProposer
snapshotNumberBytes := make([]byte, 8)
binary.BigEndian.PutUint64(snapshotNumberBytes, rs.LatestTreeSnapshot)
wb.Put(tableMerkleTreeSnapshot(step.GetEpochDelimiter().EpochNumber), snapshotNumberBytes)
latestTree := ks.merkletree.GetSnapshot(rs.LatestTreeSnapshot)
rootHash, err := latestTree.GetRootHash()
if err != nil {
log.Panicf("ks.latestTree.GetRootHash() failed: %s", err)
}
teh := &proto.EncodedTimestampedEpochHead{TimestampedEpochHead: proto.TimestampedEpochHead{
Head: proto.EncodedEpochHead{EpochHead: proto.EpochHead{
RootHash: rootHash,
PreviousSummaryHash: rs.PreviousSummaryHash,
Realm: ks.realm,
Epoch: step.GetEpochDelimiter().EpochNumber,
//.........这里部分代码省略.........
开发者ID:maditya,项目名称:coname,代码行数:101,代码来源:server.go
示例18: handleResponses
func (s *Server) handleResponses(round uint64) {
rnd := round % MaxRounds
allBlocks := <-s.rounds[rnd].dblocksChan
//store it on this server as well
s.rounds[rnd].allBlocks = allBlocks
if s.FSMode {
t := time.Now()
for i := range allBlocks {
s.rounds[rnd].upHashes[i] = allBlocks[i].Block[BlockSize:]
}
for i := range s.rounds[rnd].upHashesRdy {
if s.clientMap[i] != s.id {
continue
}
go func(i int) {
s.rounds[rnd].upHashesRdy[i] <- true
}(i)
}
var wg sync.WaitGroup
for i := 0; i < s.totalClients; i++ {
if s.clientMap[i] == s.id {
continue
}
//if it doesnt belong to me, xor things and send it over
wg.Add(1)
go func(i int, rpcServer *rpc.Client, r uint64) {
defer wg.Done()
res := ComputeResponse(allBlocks, s.maskss[r][i], s.secretss[r][i])
sha3.ShakeSum256(s.secretss[r][i], s.secretss[r][i])
sha3.ShakeSum256(s.maskss[r][i], s.maskss[r][i])
//fmt.Println(s.id, round, "mask", i, s.maskss[i])
cb := ClientBlock{
CId: i,
SId: s.id,
Block: Block{
Block: res,
Round: round,
},
}
err := rpcServer.Call("Server.PutClientBlock", cb, nil)
if err != nil {
log.Fatal("Couldn't put block: ", err)
}
}(i, s.rpcServers[s.clientMap[i]], rnd)
}
wg.Wait()
if profile {
fmt.Println(s.id, "handling_resp:", time.Since(t))
}
}
for i := range s.rounds[rnd].blocksRdy {
if s.clientMap[i] != s.id {
continue
}
go func(i int, round uint64) {
s.rounds[rnd].blocksRdy[i] <- true
}(i, round)
}
}
开发者ID:Xyroe,项目名称:riffle,代码行数:65,代码来源:server.go
示例19: main
func main() {
configPathPtr := flag.String("config", "clientconfig.json", "path to config file")
name := flag.String("name", "[email protected]", "name to be looked up")
lookupOnly := flag.Bool("lookup", false, "only lookup the name")
flag.Parse()
timeOut := 10 * time.Second
configReader, err := os.Open(*configPathPtr)
if err != nil {
log.Fatalf("Failed to open configuration file: %s", err)
}
cfg := &proto.Config{}
err = jsonpb.Unmarshal(configReader, cfg)
if err != nil {
log.Fatalf("Failed to parse configuration file: %s", err)
}
certFile := "ca.crt.pem"
caCertPEM, err := ioutil.ReadFile(certFile)
if err != nil {
log.Fatalf("couldn't read certs from %s", certFile)
}
caCertDER, caCertPEM := pem.Decode(caCertPEM)
if caCertDER == nil {
log.Fatalf("failed to parse key PEM")
}
caCert, err := x509.ParseCertificate(caCertDER.Bytes)
if err != nil {
log.Fatal(err)
}
caPool := x509.NewCertPool()
caPool.AddCert(caCert)
realm := cfg.Realms[0]
clientTLS, err := realm.ClientTLS.Config(getKey)
if err != nil {
log.Fatal(err)
}
conn, err := grpc.Dial(realm.Addr, grpc.WithTransportCredentials(credentials.NewTLS(clientTLS)), grpc.WithTimeout(timeOut))
if err != nil {
log.Fatal(err)
}
publicC := proto.NewE2EKSPublicClient(conn)
// First, do a lookup to retrieve the index
lookup, err := publicC.Lookup(context.Background(), &proto.LookupRequest{
UserId: *name,
// We don't care about any signatures here; the server just needs to tell us the index.
// We could just give an empty quorum requirement if we wanted (although I guess the
// spec actually disallows that).
QuorumRequirement: realm.VerificationPolicy.GetQuorum(),
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("looking up %s:\n", *name)
keys, err := coname.VerifyLookup(cfg, *name, lookup, time.Now())
if err != nil {
log.Fatal(err)
}
if keys == nil {
fmt.Printf("not present\n")
} else {
fmt.Printf("keys: %s\n", keys)
}
index := lookup.Index
if *lookupOnly {
return
}
// Then, do the actual update
nonce := make([]byte, 16)
_, err = rand.Read(nonce)
if err != nil {
log.Fatal(err)
}
profile := proto.EncodedProfile{
Profile: proto.Profile{
Nonce: nonce,
Keys: map[string][]byte{"abc": []byte("foo bar"), "xyz": []byte("TEST 456")},
},
}
profile.UpdateEncoding()
var commitment [64]byte
sha3.ShakeSum256(commitment[:], profile.Encoding)
var version uint64
if lookup.Entry != nil {
version = lookup.Entry.Version + 1
}
entry := proto.EncodedEntry{
Entry: proto.Entry{
Index: index,
Version: version,
UpdatePolicy: &proto.AuthorizationPolicy{
PublicKeys: make(map[uint64]*proto.PublicKey),
PolicyType: &proto.AuthorizationPolicy_Quorum{
Quorum: &proto.QuorumExpr{
Threshold: 0,
//.........这里部分代码省略.........
开发者ID:yahoo,项目名称:coname,代码行数:101,代码来源:client.go
示例20: step
// step is called by run and changes the in-memory state. No i/o allowed.
func (vr *Verifier) step(step *proto.VerifierStep, vs *proto.VerifierState, wb kv.Batch) (deferredIO func()) {
// vr: &const
// step, vs, wb: &mut
switch step.Type.(type) {
case *proto.VerifierStep_Update:
index := step.GetUpdate().NewEntry.Index
prevEntry, err := vr.getEntry(index, vs.NextEpoch)
if err := coname.VerifyUpdate(prevEntry, step.GetUpdate()); err != nil {
// the keyserver should filter all bad updates
log.Panicf("%d: bad update %v: %s", vs.NextIndex, *step, err)
}
var entryHash [32]byte
sha3.ShakeSum256(entryHash[:], step.GetUpdate().NewEntry.Encoding)
latestTree := vr.merkletree.GetSnapshot(vs.LatestTreeSnapshot)
newTree, err := latestTree.BeginModification()
if err != nil {
log.Panicf("%d: BeginModification(): %s", vs.NextIndex, err)
}
if err := newTree.Set(index, entryHash[:]); err != nil {
log.Panicf("%d: Set(%x,%x): %s", vs.NextIndex, index, entryHash[:], err)
}
vs.LatestTreeSnapshot = newTree.Flush(wb).Nr
wb.Put(tableEntries(index, vs.NextEpoch), step.GetUpdate().NewEntry.Encoding)
case *proto.VerifierStep_Epoch:
ok := coname.VerifyPolicy(vr.vs.KeyserverAuth, step.GetEpoch().Head.Encoding, step.GetEpoch().Signatures)
// the bad steps here will not get persisted to disk right now. do we want them to?
if !ok {
log.Panicf("%d: keyserver signature verification failed: %#v", vs.NextIndex, *step)
}
r := step.GetEpoch().Head
if r.Head.Realm != vr.realm {
log.Panicf("%d: seh for realm %q, expected %q: %#v", vs.NextEpoch, r.Head.Realm, vr.realm, *step)
}
if r.Head.Epoch != vs.NextEpoch {
log.Panicf("%d: got epoch %d instead: %#v", vs.NextEpoch, r.Head.Epoch, *step)
}
s := r.Head
if !bytes.Equal(s.PreviousSummaryHash, vs.PreviousSummaryHash) {
log.Panicf("%d: seh with previous summary hash %q, expected %q: %#v", vs.NextEpoch, s.PreviousSummaryHash, vs.PreviousSummaryHash, *step)
}
latestTree := vr.merkletree.GetSnapshot(vs.LatestTreeSnapshot)
rootHash, err := latestTree.GetRootHash()
if err != nil {
log.Panicf("GetRootHash() failed: %s", err)
}
if !bytes.Equal(s.RootHash, rootHash) {
log.Panicf("%d: seh with root hash %q, expected %q: %#v", vs.NextEpoch, s.RootHash, rootHash, *step)
}
seh := &proto.SignedEpochHead{
Head: proto.EncodedTimestampedEpochHead{TimestampedEpochHead: proto.TimestampedEpochHead{
Head: s,
Timestamp: proto.Time(time.Now()),
}, Encoding: nil},
Signatures: make(map[uint64][]byte, 1),
}
if vs.PreviousSummaryHash == nil {
vs.PreviousSummaryHash = make([]byte, 64)
}
sha3.ShakeSum256(vs.PreviousSummaryHash[:], seh.Head.Head.Encoding)
seh.Head.UpdateEncoding()
seh.Signatures[vr.id] = ed25519.Sign(vr.signingKey, proto.MustMarshal(&seh.Head))[:]
wb.Put(tableRatifications(vs.NextEpoch, vr.id), proto.MustMarshal(seh))
vs.NextEpoch++
return func() {
_, err := vr.keyserver.PushRatification(vr.ctx, seh)
if err != nil {
log.Printf("PushRatification: %s", err)
}
}
default:
log.Panicf("%d: unknown step: %#v", vs.NextIndex, *step)
}
return
}
开发者ID:yahoo,项目名称:coname,代码行数:76,代码来源:verifier.go
注:本文中的golang.org/x/crypto/sha3.ShakeSum256函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论