本文整理汇总了Golang中github.com/mutecomm/mute/util/times.Now函数的典型用法代码示例。如果您正苦于以下问题:Golang Now函数的具体用法?Golang Now怎么用?Golang Now使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Now函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: KeyInit
// KeyInit returns a new KeyInit message for the given UID message. It also
// returns the pubKeyHash and privateKey for convenient further use.
// msgcount must increase for each message of the same type and user.
// notafter is the unixtime after which the key(s) should not be used anymore.
// notbefore is the unixtime before which the key(s) should not be used yet.
// fallback determines if the key may serve as a fallback key.
// repoURI is URI of the corresponding KeyInit repository.
// Necessary randomness is read from rand.
func (msg *Message) KeyInit(
msgcount, notafter, notbefore uint64,
fallback bool,
repoURI, mixaddress, nymaddress string,
rand io.Reader,
) (ki *KeyInit, pubKeyHash, privateKey string, err error) {
var keyInit KeyInit
// time checks
if notbefore >= notafter {
log.Error(ErrInvalidTimes)
return nil, "", "", ErrInvalidTimes
}
if notafter < uint64(times.Now()) {
log.Error(ErrExpired)
return nil, "", "", ErrExpired
}
if notafter > uint64(times.Now())+MaxNotAfter {
log.Error(ErrFuture)
return nil, "", "", ErrFuture
}
// init
keyInit.Contents.VERSION = ProtocolVersion
keyInit.Contents.MSGCOUNT = msgcount
keyInit.Contents.NOTAFTER = notafter
keyInit.Contents.NOTBEFORE = notbefore
keyInit.Contents.FALLBACK = fallback
keyHash, err := base64.Decode(msg.UIDContent.SIGKEY.HASH)
if err != nil {
return nil, "", "", err
}
keyInit.Contents.SIGKEYHASH = base64.Encode(cipher.SHA512(keyHash))
// make sure REPOURIS is set to the first REPOURI of UIDContent.REPOURIS
// TODO: support different KeyInit repository configurations
if repoURI != msg.UIDContent.REPOURIS[0] {
return nil, "", "",
log.Error("uri: repoURI differs from msg.UIDContent.REPOURIS[0]")
}
keyInit.Contents.REPOURI = repoURI
// create SessionAnchor
sa, sah, pubKeyHash, privateKey, err := msg.sessionAnchor(keyHash,
mixaddress, nymaddress, rand)
if err != nil {
return nil, "", "", err
}
keyInit.Contents.SESSIONANCHOR = sa
keyInit.Contents.SESSIONANCHORHASH = sah
// sign KeyInit: the content doesn't have to be hashed, because Ed25519 is
// already taking care of that.
sig := msg.UIDContent.SIGKEY.ed25519Key.Sign(keyInit.Contents.json())
keyInit.SIGNATURE = base64.Encode(sig)
ki = &keyInit
return
}
示例2: TestKeyList
func TestKeyList(t *testing.T) {
now := times.Now()
timeNow = func() int64 { return now - 2 }
_, privkey, _ := ed25519.GenerateKey(rand.Reader)
kl := New(privkey, "[email protected]", 5, 5, testDir)
kl.AddKey()
kl.AddKey()
timeNow = func() int64 { return now }
kl.AddKey()
timeNow = func() int64 { return times.Now() }
marshalled := kl.Marshal()
kl2 := New(privkey, "[email protected]", 5, 5, testDir)
err := kl2.Unmarshal(marshalled)
if err != nil {
t.Errorf("Unmarshal failed: %s", err)
}
for k := range kl.Keys {
if _, ok := kl2.Keys[k]; !ok {
t.Errorf("Not found after unmarshal: %x", k)
}
}
first, last := kl2.GetBoundaryTime()
if last-first < 1 {
t.Error("GetBoundaryTime failed")
}
timeNow = func() int64 { return now + 4 }
// kl2.Maintain()
kl2.Expire()
if len(kl2.Keys) != 1 {
t.Error("Expire wrong number of keys")
}
timeNow = func() int64 { return times.Now() + 10 }
kl2.AddKey()
kl2.Expire()
if len(kl2.Keys) != 1 {
t.Error("Expire wrong number of keys")
}
timeNow = func() int64 { return time.Now().Unix() }
if !testing.Short() {
kl2 := New(privkey, "[email protected]", 20, 10, testDir)
kl2.Maintain()
time.Sleep(time.Second * 33)
close(kl2.stopchan)
time.Sleep(time.Second * 1)
if len(kl2.Keys) > 4 || len(kl2.Keys) < 2 {
t.Error("Expire/Add maintainer inconsistent")
}
}
}
示例3: TestPublicKeyInit
func TestPublicKeyInit(t *testing.T) {
tmpdir, keyDB, err := createDB()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
defer keyDB.Close()
msg, err := uid.Create("[email protected]", false, "", "", uid.Strict,
hashchain.TestEntry, cipher.RandReader)
if err != nil {
t.Fatal(err)
}
now := uint64(times.Now())
ki, _, _, err := msg.KeyInit(1, now+times.Day, now-times.Day,
false, "mute.berlin", "", "", cipher.RandReader)
if err != nil {
t.Fatal(err)
}
if err := keyDB.AddPublicKeyInit(ki); err != nil {
t.Fatal(err)
}
rKI, err := keyDB.GetPublicKeyInit(ki.SigKeyHash())
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(rKI.JSON(), ki.JSON()) {
t.Error("KeyInits differ")
}
}
示例4: TestPrivateKeyInit
func TestPrivateKeyInit(t *testing.T) {
tmpdir, keyDB, err := createDB()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
defer keyDB.Close()
msg, err := uid.Create("[email protected]", false, "", "", uid.Strict,
hashchain.TestEntry, cipher.RandReader)
if err != nil {
t.Fatal(err)
}
now := uint64(times.Now())
ki, pubKeyHash, privateKey, err := msg.KeyInit(1, now+times.Day, now-times.Day,
false, "mute.berlin", "", "", cipher.RandReader)
if err != nil {
t.Fatal(err)
}
err = keyDB.AddPrivateKeyInit(ki, pubKeyHash, msg.SigPubKey(), privateKey,
"/63l/c3XB5yimoGKv6GS9TjuiM3PKVH/H/dlhnQixeIRsFRkWRl8fjXmKyQl5bk4N7DjkBPg/1GQVndhG+HWAg==")
if err != nil {
t.Fatal(err)
}
rKI, rSigPubKey, rPrivKey, err := keyDB.GetPrivateKeyInit(pubKeyHash)
if !bytes.Equal(rKI.JSON(), ki.JSON()) {
t.Error("KeyInits differ")
}
if rSigPubKey != msg.SigPubKey() {
t.Error("SigPubKeys differ")
}
if rPrivKey != privateKey {
t.Error("PrivKeys differ")
}
}
示例5: TestCheckToken
func TestCheckToken(t *testing.T) {
now := uint64(times.Now()) / SkewWindow
pubkey, privkey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("Key generation failed: %s", err)
}
authtoken := CreateToken(pubkey, privkey, 1)
pubkey2, ltime, lcounter, err := authtoken.CheckToken()
if err != nil {
t.Errorf("Token verification failed: %s", err)
}
if *pubkey2 != *pubkey {
t.Errorf("Token decode failed, pubkey does not match: %x!=%x", *pubkey2, *pubkey)
}
if lcounter != 1 {
t.Errorf("Token decode failed. Counter %d!=1", lcounter)
}
if uint64(math.Abs(float64(ltime-now))) > 1 {
t.Errorf("Token decode failed. Time: %d!=%d", now, ltime)
}
authtoken[0] = 0x00
_, _, _, err = authtoken.CheckToken()
if err == nil {
t.Error("Token verification MUST fail")
}
}
示例6: ExpireUnusable
// ExpireUnusable expires all tokens that cannot be used anymore (expired). Returns bool if it should be called
// again since it only expires 10 tokens at a time
func (ws *Storage) ExpireUnusable() bool {
var hashS string
var counted int
var tokens [][]byte
expireTime := times.Now() - ExpireEdge
rows, err := ws.finalExpireQuery.Query(expireTime)
if err != nil {
return false
}
for rows.Next() {
if err := rows.Scan(&hashS); err == nil {
tokenHash, err := hex.DecodeString(hashS)
if err == nil {
counted++
tokens = append(tokens, tokenHash)
}
}
}
rows.Close()
for _, token := range tokens {
ws.DelToken(token)
}
if counted >= 10 {
return true
}
return false
}
示例7: Current
// Current returns the current key and the previous key.
func (kp *KeyPool) Current() (*signkeys.KeyPair, *signkeys.KeyPair, error) {
if kp.Generator.PrivateKey == nil {
return nil, nil, ErrNoGenerator
}
generate := false
kp.mapMutex.Lock()
defer kp.mapMutex.Unlock()
if kp.currentKey == nil {
// Always generate if we dont have one yet
generate = true
} else if kp.currentKey.PublicKey.Expire < times.Now()-kp.Generator.ExpireTime/2 {
// Key has half expired, generate new one
generate = true
}
if generate {
newKey, err := kp.Generator.GenKey()
if err != nil {
return nil, nil, err
}
// Write currentKey to file
err = kp.WriteKey(&newKey.PublicKey)
if err != nil {
return nil, nil, err
}
if kp.currentKey != nil {
kp.previousKey = kp.currentKey
}
kp.currentKey = newKey
kp.keys[kp.currentKey.PublicKey.KeyID] = &newKey.PublicKey
}
return kp.currentKey, kp.previousKey, nil
}
示例8: TestSessionAnchor
func TestSessionAnchor(t *testing.T) {
// create UID message
msg, err := Create("[email protected]", false, "", "", Strict,
hashchain.TestEntry, cipher.RandReader)
if err != nil {
t.Fatal(err)
}
// KeyInit
now := uint64(times.Now())
ki, _, privKey, err := msg.KeyInit(1, now+times.Day, now-times.Day,
false, "mute.berlin", "", "", cipher.RandReader)
if err != nil {
t.Fatal(err)
}
// SesionAnchor
sa, err := ki.SessionAnchor(msg.SigPubKey())
if err != nil {
t.Fatal(err)
}
// check private key methods
if err := sa.SetPrivateKey(privKey); err != nil {
t.Fatal(err)
}
if privKey != sa.PrivateKey() {
t.Fatal("private keys differ")
}
}
示例9: CleanLocks
// CleanLocks cleans all locks. If force is true all locks are removed, not only expired locks
func (ws *Storage) CleanLocks(force bool) {
locktime := times.Now() + MaxLockAge
if force {
locktime = int64(^uint32(0)) // MaxUInt32
}
ws.cleanLocksQuery.Exec(locktime)
}
示例10: GenerateCertificate
// GenerateCertificate returns a signed and encoded SortedMap.
func (sm StringMap) GenerateCertificate(privKey *[ed25519.PrivateKeySize]byte) ([]byte, error) {
so := sm.Sort()
sigmap := new(SignedMap)
sigmap.SignDate = uint64(times.Now())
sigmap.Signature = so.Sign(sigmap.SignDate, privKey)
sigmap.Config = sm
return sigmap.Marshal()
}
示例11: TestKeyEntry
func TestKeyEntry(t *testing.T) {
// create UID message
msg, err := Create("[email protected]", false, "", "", Strict,
hashchain.TestEntry, cipher.RandReader)
if err != nil {
t.Fatal(err)
}
// KeyInit
now := uint64(times.Now())
ki, _, privateKey, err := msg.KeyInit(1, now+times.Day, now-times.Day,
false, "mute.berlin", "", "", cipher.RandReader)
if err != nil {
t.Fatal(err)
}
// KeyEntry
ke, err := ki.KeyEntryECDHE25519(msg.SigPubKey())
if err != nil {
t.Fatal(err)
}
// verify consistency
if err := ke.Verify(); err != nil {
t.Fatal(err)
}
// equal
if !KeyEntryEqual(ke, ke) {
t.Error("ke should be equal to itself")
}
a := ke
var b KeyEntry
b.CIPHERSUITE = a.CIPHERSUITE
b.FUNCTION = a.FUNCTION
b.HASH = a.HASH
b.PUBKEY = a.PUBKEY
if !KeyEntryEqual(a, &b) {
t.Error("a and b should be equal to itself")
}
// private key check
if err := ke.SetPrivateKey(privateKey); err != nil {
t.Fatal(err)
}
privKey := ke.PrivateKey32()
if privateKey != base64.Encode(privKey[:]) {
t.Error("private keys differ")
}
// public key check
var publicKey [32]byte
curve25519.ScalarBaseMult(&publicKey, privKey)
pubKey := ke.PublicKey32()
if !bytes.Equal(publicKey[:], pubKey[:]) {
t.Error("public keys differ")
}
}
示例12: lookup
// lookup a public key from keypool without lock
func (kp *KeyPool) lookup(keyid [signkeys.KeyIDSize]byte) (*signkeys.PublicKey, error) {
if d, ok := kp.keys[keyid]; ok {
if d.Expire > times.Now() {
return d, nil
}
return nil, ErrExpired
}
return nil, ErrNotFound
}
示例13: Verify
// Verify verifies that the KeyInit is valid and contains a valid ECDHE25519
// key.
func (ki *KeyInit) Verify(keyInitRepositoryURIs []string, sigPubKey string) error {
// The REPOURI points to this KeyInit Repository
if !util.ContainsString(keyInitRepositoryURIs, ki.Contents.REPOURI) {
log.Error(ErrRepoURI)
return ErrRepoURI
}
// verify that SESSIONANCHORHASH matches decrypted SESSIONANCHOR
sa, err := ki.SessionAnchor(sigPubKey)
if err != nil {
return err
}
// get KeyEntry message from SessionAnchor
ke, err := sa.KeyEntry("ECDHE25519")
if err != nil {
return err
}
// verify KeyEntry message
if err := ke.Verify(); err != nil {
return err
}
// NOTAFTER and NOTBEFORE are valid
if ki.Contents.NOTBEFORE >= ki.Contents.NOTAFTER {
log.Error(ErrInvalidTimes)
return ErrInvalidTimes
}
// not expired
if ki.Contents.NOTAFTER < uint64(times.Now()) {
log.Error(ErrExpired)
return ErrExpired
}
// SIGNATURE was made with UIDMessage.UIDContent.SIGKEY over Contents
var ed25519Key cipher.Ed25519Key
sig, err := base64.Decode(ki.SIGNATURE)
if err != nil {
return err
}
pubKey, err := base64.Decode(sigPubKey)
if err != nil {
return err
}
// create ed25519 key
ed25519Key.SetPublicKey(pubKey)
// verify self-signature
if !ed25519Key.Verify(ki.Contents.json(), sig) {
log.Error(ErrInvalidKeyInitSig)
return ErrInvalidKeyInitSig
}
return nil
}
示例14: ParseAddress
// ParseAddress parses an address.
func ParseAddress(address []byte) (*Address, error) {
a := new(Address)
_, err := asn1.Unmarshal(address, a)
if err != nil {
return nil, err
}
if a.Expire < times.Now() {
return nil, ErrExpired
}
return a, nil
}
示例15: encrypt
func encrypt(sign bool, flipUIDs bool) (
sender, recipient *uid.Message,
w bytes.Buffer,
recipientTemp *uid.KeyEntry,
privateKey string,
err error,
) {
sender, err = uid.Create("[email protected]", false, "", "", uid.Strict,
hashchain.TestEntry, cipher.RandReader)
if err != nil {
return
}
recipient, err = uid.Create("[email protected]", false, "", "", uid.Strict,
hashchain.TestEntry, cipher.RandReader)
if err != nil {
return
}
if flipUIDs {
sender, recipient = recipient, sender
}
r := bytes.NewBufferString(msgs.Message1)
now := uint64(times.Now())
recipientKI, _, privateKey, err := recipient.KeyInit(1, now+times.Day, now-times.Day,
false, "mute.berlin", "", "", cipher.RandReader)
if err != nil {
return
}
recipientTemp, err = recipientKI.KeyEntryECDHE25519(recipient.SigPubKey())
if err != nil {
return
}
// encrypt
var privateSigKey *[64]byte
if sign {
privateSigKey = sender.PrivateSigKey64()
}
ms := memstore.New()
ms.AddPublicKeyEntry(recipient.Identity(), recipientTemp)
args := &EncryptArgs{
Writer: &w,
From: sender,
To: recipient,
SenderLastKeychainHash: hashchain.TestEntry,
PrivateSigKey: privateSigKey,
Reader: r,
Rand: cipher.RandReader,
KeyStore: ms,
}
if _, err = Encrypt(args); err != nil {
return
}
return
}