Ejemplo n.º 1
0
func (ch *Channel) SignEnvelope(ev wire.Envelope) (*wire.Envelope, error) {
	// Put signature in correct slot
	switch ch.Me {
	case 1:
		ev.Signature1 = ed25519.Sign(sliceTo64Byte(ch.Identity1.Privkey), ev.Payload)[:]
	case 2:
		ev.Signature2 = ed25519.Sign(sliceTo64Byte(ch.Identity2.Privkey), ev.Payload)[:]
	}

	return &ev, nil
}
Ejemplo n.º 2
0
func (ks *Keyserver) updateSignatureProposer() {
	// invariant: do not access the db if ThisReplicaNeedsToSignLastEpoch = false
	want := ks.rs.ThisReplicaNeedsToSignLastEpoch
	have := ks.signatureProposer != nil
	if have == want {
		return
	}

	switch want {
	case true:
		tehBytes, err := ks.db.Get(tableEpochHeads(ks.rs.LastEpochDelimiter.EpochNumber))
		if err != nil {
			log.Panicf("ThisReplicaNeedsToSignLastEpoch but no TEH for last epoch in db: %s", err)
		}
		var teh proto.EncodedTimestampedEpochHead
		if err := teh.Unmarshal(tehBytes); err != nil {
			log.Panicf("tableEpochHeads(%d) invalid: %s", ks.rs.LastEpochDelimiter.EpochNumber, err)
		}
		seh := &proto.SignedEpochHead{
			Head:       teh,
			Signatures: map[uint64][]byte{ks.replicaID: ed25519.Sign(ks.sehKey, tehBytes)[:]},
		}
		ks.signatureProposer = StartProposer(ks.log, ks.clk, ks.retryProposalInterval,
			replication.LogEntry{Data: proto.MustMarshal(&proto.KeyserverStep{Type: &proto.KeyserverStep_ReplicaSigned{ReplicaSigned: seh}})})
	case false:
		ks.signatureProposer.Stop()
		ks.signatureProposer = nil
	}
}
Ejemplo n.º 3
0
// Sign signs the message with the private key using Ed25519.
func Sign(priv *PrivateKey, message []byte) ([]byte, bool) {
	if !priv.Valid() {
		return nil, false
	}
	sig := ed25519.Sign(priv.S, message)
	return sig[:], true
}
Ejemplo n.º 4
0
func (u *User) SetKeys(pubkey *[ed25519.PublicKeySize]byte, privkey *[ed25519.PrivateKeySize]byte) (err error) {
	sign := ed25519.Sign(privkey, signtestmsg)
	if ed25519.Verify(pubkey, signtestmsg, sign) {
		return nil
	}
	return ErrInvalidKey
}
Ejemplo n.º 5
0
func replyWithChallenge(w http.ResponseWriter, login string) {

	var defaultSaltRaw [32]byte
	rand.Read(defaultSaltRaw[:])
	salt := base64.StdEncoding.EncodeToString(defaultSaltRaw[:])

	u, ok := users[login]
	if ok {
		salt = u.Salt
	}

	var token [32]byte
	rand.Read(token[:])
	sig := ed25519.Sign(signingKey, token[:])

	signedTokenRaw := make([]byte, len(token)+len(sig))
	copy(signedTokenRaw, token[:])
	copy(signedTokenRaw[len(token):], sig[:])
	signedToken := base64.StdEncoding.EncodeToString(signedTokenRaw)

	err := json.NewEncoder(w).Encode(challenge{signedToken, salt})
	if err != nil {
		log.Println(err)
		http.Error(w, "Error with your request", http.StatusBadRequest)
	}
}
Ejemplo n.º 6
0
// Sign returns a signature for a given blob
func (s *Ed25519Signer) Sign(request *pb.SignatureRequest) (*pb.Signature, error) {
	priv := [ed25519.PrivateKeySize]byte{}
	copy(priv[:], s.privateKey.Private())
	sig := ed25519.Sign(&priv, request.Content)

	return &pb.Signature{KeyInfo: &pb.KeyInfo{KeyID: &pb.KeyID{ID: s.privateKey.ID()}, Algorithm: &pb.Algorithm{Algorithm: data.ED25519Key.String()}}, Content: sig[:]}, nil
}
Ejemplo n.º 7
0
func (ek *Ed25519PrivateKey) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
	signature := ed25519.Sign(ek.bytes, data)
	return &ssh.Signature{
		Format: ek.PublicKey().Type(),
		Blob:   (*signature)[:],
	}, nil
}
Ejemplo n.º 8
0
func (p *RawPacket) Sign(privk *[ed25519.PrivateKeySize]byte) {
	length := uint16(len(p.Payload))
	buf := make([]byte, length+4)
	binary.BigEndian.PutUint16(buf, length)
	binary.BigEndian.PutUint16(buf[2:], p.Frametype)
	copy(buf[4:], p.Payload)
	p.Signature = ed25519.Sign(privk, buf)
}
Ejemplo n.º 9
0
// Create a factom.Entry and commit/reveal
func (a *APICall) Factomize() error {
	type entryBody struct {
		APIMethod  string
		ReturnData string
		Timestamp  int64
	}
	b := new(entryBody)

	b.APIMethod = a.APIMethod

	// get the ReturnData from the api call
	resp, err := http.Get(a.APIMethod)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return fmt.Errorf(string(data))
	}
	b.ReturnData = string(data)

	// get the current time
	b.Timestamp = time.Now().Unix()

	// create the factom entry
	e := factom.NewEntry()

	e.ChainID = a.ChainID
	if e.Content, err = json.Marshal(b); err != nil {
		return err
	}

	// Write the signature of the Entry Content to the first ExtID
	e.ExtIDs = append(e.ExtIDs, func() []byte {
		sec := new([64]byte)
		if s, err := hex.DecodeString(a.SecKey); err != nil {
			log.Fatal(err)
		} else {
			copy(sec[:], s)
		}
		return ed.Sign(sec, e.Content)[:]
	}())

	// Commit+Reveal the Entry to the Factom Network
	if err := factom.CommitEntry(e, a.ECAddr); err != nil {
		return err
	}
	time.Sleep(10 * time.Second)
	if err := factom.RevealEntry(e); err != nil {
		return err
	}

	return nil
}
Ejemplo n.º 10
0
func SignKeys(keys []*[32]byte, sk *[64]byte) [][]byte {

	pkList := make([][]byte, 0)
	for _, key := range keys {
		signature := ed25519.Sign(sk, key[:])
		pkList = append(pkList, append(append([]byte{}, key[:]...), signature[:]...))
	}
	return pkList
}
Ejemplo n.º 11
0
func (ch *Channel) CosignProposedUpdateTx() *wire.Envelope {
	ev := ch.TheirProposedUpdateTxEnvelope
	ev.Signatures[ch.Me] = ed25519.Sign(sliceTo64Byte(ch.Account.Privkey), ev.Payload)[:]

	ch.LastFullUpdateTx = ch.TheirProposedUpdateTx
	ch.LastFullUpdateTxEnvelope = ch.TheirProposedUpdateTxEnvelope

	return ev
}
Ejemplo n.º 12
0
// Sign a messageid.
func (keypair *SignKeyPair) Sign(msgID [MessageIDSize]byte) *[SignHeaderSize]byte {
	signHeader := new([SignHeaderSize]byte)
	signHeader[0] = byte(Version)
	copy(signHeader[signHeaderPubkeyStart:signHeaderPubkeyEnd], keypair.PublicKey[:])
	copy(signHeader[signHeaderNonceStart:signHeaderNonceEnd], keypair.Nonce[:])
	signature := ed25519.Sign(keypair.PrivateKey, msgID[:])
	copy(signHeader[signHeaderSignatureStart:signHeaderSignatureEnd], signature[:])
	copy(signHeader[signHeaderMsgIDStart:signHeaderMsgIDEnd], msgID[:])
	return signHeader
}
Ejemplo n.º 13
0
// Sign a SpendPacket.
func (s *SpendPacket) Sign(privkey *[ed25519.PrivateKeySize]byte) {
	if privkey == nil {
		s.Signature = []byte{0x00}
		return
	}
	sig := ed25519.Sign(privkey, s.Image())
	s.Signature = make([]byte, len(sig))
	copy(s.Signature, sig[:])
	return
}
Ejemplo n.º 14
0
// Sign a ReissuePacket.
func (p *ReissuePacket) Sign(privkey *[ed25519.PrivateKeySize]byte) {
	if privkey == nil {
		p.Signature = []byte{0x00}
		return
	}
	sig := ed25519.Sign(privkey, p.Image())
	p.Signature = make([]byte, len(sig))
	copy(p.Signature, sig[:])
	return
}
Ejemplo n.º 15
0
// ED25519Signature returns the ED25519 signature of data using the key.
func ED25519Signature(key, data []byte) ([]byte, error) {
	if len(key) != ed25519.PrivateKeySize {
		return nil, fmt.Errorf("Invalid size of key (%v)", len(key))
	}

	var k [ed25519.PrivateKeySize]byte
	copy(k[:], key)
	signature := ed25519.Sign(&k, data)

	return signature[:], nil
}
Ejemplo n.º 16
0
func ed25519Sign(privKey data.PrivateKey, message []byte) ([]byte, error) {
	if privKey.Algorithm() != data.ED25519Key {
		return nil, fmt.Errorf("private key type not supported: %s", privKey.Algorithm())
	}

	priv := [ed25519.PrivateKeySize]byte{}
	copy(priv[:], privKey.Private()[ed25519.PublicKeySize:])
	sig := ed25519.Sign(&priv, message)

	return sig[:], nil
}
Ejemplo n.º 17
0
// CounterSignToken creates a counter-signature for token
// recPubKey is the public key of Bob. Returns true/false and the countersigned prooftoken
func CounterSignToken(proof *[ProofTokenSize]byte, recPubKey *[ed25519.PublicKeySize]byte, recPrivKey *[ed25519.PrivateKeySize]byte) (bool, *[ProofTokenSignedSize]byte) {
	var counterSig [ProofTokenSignedSize]byte
	ok, _, _ := VerifyProofToken(proof, recPubKey)
	if !ok {
		return false, nil
	}
	copy(counterSig[:ProofTokenSize], proof[:ProofTokenSize])
	sig := ed25519.Sign(recPrivKey, proof[:ProofTokenSize])
	copy(counterSig[ProofTokenSize:], sig[:ed25519.SignatureSize])
	return true, &counterSig
}
Ejemplo n.º 18
0
// Sign attempts to sign a a message with a provideded key.
func Sign(sk, message []byte) (signature []byte, err error) {
	if len(message) == 0 {
		return nil, errors.New("cannot sign an empty message")
	}
	key, err := ToByteArray64(sk)
	if err != nil {
		return nil, errors.New("invalid signing key")
	}

	signature = ed25519.Sign(key, message)[:]
	return
}
Ejemplo n.º 19
0
func signKEX(kex *[kexPubSize + SignatureSize]byte, signer *[IdentityPrivateSize]byte) bool {
	if kex == nil {
		return false
	}

	if signer == nil {
		return true
	}

	sig := ed25519.Sign(signer, kex[:kexPubSize])
	copy(kex[kexPubSize:], sig[:])
	return true
}
Ejemplo n.º 20
0
// Unmarshal d into keypair.
func (keypair SignKeyPair) Unmarshal(d []byte) (*SignKeyPair, error) {
	kp := new(SignKeyPair)
	kp.PublicKey = new([SignerPubKeySize]byte)
	kp.PrivateKey = new([ed25519.PrivateKeySize]byte)
	copy(kp.PublicKey[:], d[0:SignerPubKeySize])
	copy(kp.PrivateKey[:], d[SignerPubKeySize:SignerPubKeySize+ed25519.PrivateKeySize])
	copy(kp.Nonce[:], d[SignerPubKeySize+ed25519.PrivateKeySize:SignerPubKeySize+ed25519.PrivateKeySize+hashcash.NonceSize])
	kp.Bits = d[SignerPubKeySize+ed25519.PrivateKeySize+hashcash.NonceSize]
	msg := []byte("validationtest")
	if ed25519.Verify(kp.PublicKey, msg, ed25519.Sign(kp.PrivateKey, msg)) {
		return kp, nil
	}
	return nil, ErrNoKeyFound
}
Ejemplo n.º 21
0
func (s *scriptState) buildHMACDelivery(to int, message []byte, seed int) *pond.Request {
	pub, priv, digest := s.makeOneTimePubKey(to, seed)
	sig := ed25519.Sign(priv, message)

	return &pond.Request{
		Deliver: &pond.Delivery{
			To:               s.publicIdentities[to][:],
			Message:          message,
			OneTimePublicKey: pub[:],
			HmacOfPublicKey:  proto.Uint64(digest),
			OneTimeSignature: sig[:],
		},
	}
}
Ejemplo n.º 22
0
// SignProofToken generates a signproof
// recPubkey is Bob's public key, sendPubkey and sendPrivkey are Alice's. time is the timestamp to embed
// returns the prooftoken
func SignProofToken(time int64, recPubkey, sendPubkey *[ed25519.PublicKeySize]byte, sendPrivKey *[ed25519.PrivateKeySize]byte) *[ProofTokenSize]byte {
	var proof [ProofTokenSize]byte
	timeB := make([]byte, 8)
	binary.BigEndian.PutUint64(timeB, uint64(time))
	cur := 0
	copy(proof[cur:cur+8], timeB[:])
	cur += 8
	copy(proof[cur:cur+ed25519.PublicKeySize], recPubkey[:])
	cur += ed25519.PublicKeySize
	copy(proof[cur:cur+ed25519.PublicKeySize], sendPubkey[:])
	cur += ed25519.PublicKeySize
	sig := ed25519.Sign(sendPrivKey, proof[:cur])
	copy(proof[cur:cur+ed25519.SignatureSize], sig[:])
	return &proof
}
Ejemplo n.º 23
0
func (e *Ed25519) Sign(keyIDs []string, toSign []byte) ([]data.Signature, error) {
	signatures := make([]data.Signature, 0, len(keyIDs))
	for _, kID := range keyIDs {
		priv := [ed25519.PrivateKeySize]byte{}
		copy(priv[:], e.keys[kID].Private())
		sig := ed25519.Sign(&priv, toSign)
		signatures = append(signatures, data.Signature{
			KeyID:     kID,
			Method:    data.EDDSASignature,
			Signature: sig[:],
		})
	}
	return signatures, nil

}
Ejemplo n.º 24
0
func TestSignatureSize(t *testing.T) {
	t.Parallel()
	_, privKey, err := ed25519.GenerateKey(cipher.RandReader)
	if err != nil {
		t.Fatal(err)
	}
	sig := ed25519.Sign(privKey, cipher.SHA512([]byte("test")))
	ih := newInnerHeader(signatureType, false, sig[:])
	var buf bytes.Buffer
	if err := ih.write(&buf); err != nil {
		t.Fatal(err)
	}
	oh := newOuterHeader(encryptedPacket, 4, buf.Bytes())
	if oh.size() != signatureSize {
		t.Errorf("oh.size() = %d != %d", oh.size(), signatureSize)
	}
}
Ejemplo n.º 25
0
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")
	}
}
Ejemplo n.º 26
0
// NewChannel makes a new channel with the supplied information. `ident1` must
// have a valid private key, and is assumed to correspond to an account that
// we control.
func NewChannel(
	ident1 *Identity,
	ident2 *Identity,
	amount1 uint32,
	amount2 uint32,
	holdPeriod uint32,
) (*Channel, error) {
	b, err := randomBytes(32)
	chID := string(b)
	if err != nil {
		return nil, err
	}

	ch := &Channel{
		ChannelID: chID,
		OpeningTx: &wire.OpeningTx{
			ChannelID:  chID,
			Pubkey1:    ident1.Pubkey,
			Pubkey2:    ident2.Pubkey,
			Amount1:    amount1,
			Amount2:    amount2,
			HoldPeriod: holdPeriod,
		},
		Me:    1,
		State: schema.Channel_PendingOpen,
	}

	// Serialize update transaction
	data, err := proto.Marshal(ch.OpeningTx)
	if err != nil {
		return nil, err
	}

	// Make new envelope
	ch.OpeningTxEnvelope = &wire.Envelope{
		Type:       wire.Envelope_UpdateTxProposal,
		Payload:    data,
		Signature1: ed25519.Sign(sliceTo64Byte(ident1.Privkey), data)[:],
	}

	return ch, nil
}
Ejemplo n.º 27
0
func TestSign(t *testing.T) {
	var zero zeroReader
	public, private, _ := ed25519.GenerateKey(zero)

	blob := []byte("test message")

	directSig := ed25519.Sign(private, blob)
	directSigHex := hex.EncodeToString(directSig[:])

	key := data.NewPrivateKey(data.ED25519Key, public[:], private[:])
	signer := api.NewEd25519Signer(key)

	sigRequest := &pb.SignatureRequest{KeyID: &pb.KeyID{ID: key.ID()}, Content: blob}

	sig, err := signer.Sign(sigRequest)
	assert.Nil(t, err)
	signatureHex := fmt.Sprintf("%x", sig.Content)

	assert.Equal(t, directSigHex, signatureHex)
	assert.Equal(t, sig.KeyInfo.KeyID.ID, key.ID())
}
Ejemplo n.º 28
0
// Vouch a self-signed certificate that is about to be created with an Ed25519 signature.
func Vouch(signPub *[ed25519.PublicKeySize]byte, signPriv *[ed25519.PrivateKeySize]byte, cert *x509.Certificate, tlsPub interface{}) error {
	// note: this is so early the cert is not serialized yet, can't use those fields
	tlsPubDer, err := x509.MarshalPKIXPublicKey(tlsPub)
	if err != nil {
		return err
	}
	msg := make([]byte, 0, len(prefix)+8+len(tlsPubDer))
	msg = append(msg, prefix...)
	var now [8]byte
	binary.LittleEndian.PutUint64(now[:], uint64(cert.NotAfter.Unix()))
	msg = append(msg, now[:]...)
	msg = append(msg, tlsPubDer...)

	env := make([]byte, 0, ed25519.PublicKeySize+ed25519.SignatureSize)
	env = append(env, signPub[:]...)
	sig := ed25519.Sign(signPriv, msg)
	env = append(env, sig[:]...)
	ext := pkix.Extension{Id: oid, Value: env}
	cert.ExtraExtensions = append(cert.ExtraExtensions, ext)
	return nil
}
Ejemplo n.º 29
0
// NewSession creates a new session, and returns a signed key blob
// that should be sent to the peer.
func (id *Identity) NewSession() (*[SessionKeySize]byte, *Session, error) {
	s := &Session{
		sendKey: new([32]byte),
		recvKey: new([32]byte),
	}

	pub, priv, err := GenerateKeyPair()
	if err != nil {
		return nil, nil, err
	}

	// Store the key here until the session is complete.
	s.priv = priv

	signedBlob := new([SessionKeySize]byte)
	copy(signedBlob[:], id.public[:])
	copy(signedBlob[ed25519.PublicKeySize:], pub[:])
	sig := ed25519.Sign(id.private, signedBlob[:blobDataSize])
	copy(signedBlob[blobDataSize:], sig[:])
	return signedBlob, s, nil
}
Ejemplo n.º 30
0
// GenKey generates a new key structure.
func (kg KeyGenerator) GenKey() (*KeyPair, error) {
	if kg.PrivateKey == nil {
		return nil, ErrNoSigner
	}
	privateKey, publicKey, err := kg.Curve.GenerateKey()
	if err != nil {
		return nil, err
	}
	k := &KeyPair{
		PrivateKey: privateKey,
		PublicKey: PublicKey{
			PublicKey: *publicKey,
			Expire:    times.Now() + kg.ExpireTime,
			Usage:     kg.Usage,
			Signer:    *kg.PublicKey,
		},
	}
	// Create signature
	k.PublicKey.KeyID = k.PublicKey.CalcKeyID()
	sig := ed25519.Sign(kg.PrivateKey, k.PublicKey.KeyID[:])
	k.PublicKey.Signature = *sig
	return k, nil
}