Пример #1
0
//intenal, may fail
//may return nil
func pubkeyFromSeckey(seckey []byte) []byte {
	if len(seckey) != 32 {
		log.Panic("seckey length invalid")
	}

	if secp.SeckeyIsValid(seckey) != 1 {
		log.Panic("always ensure seckey is valid")
		return nil
	}

	var pubkey []byte = secp.GeneratePublicKey(seckey) //always returns true
	if pubkey == nil {
		log.Panic("ERROR: impossible, secp.BaseMultiply always returns true")
		return nil
	}
	if len(pubkey) != 33 {
		log.Panic("ERROR: impossible, invalid pubkey length")
	}

	if ret := secp.PubkeyIsValid(pubkey); ret != 1 {
		log.Panic("ERROR: pubkey invald, ret=%s", ret)
		return nil
	}

	if ret := VerifyPubkey(pubkey); ret != 1 {

		log.Printf("seckey= %s", hex.EncodeToString(seckey))
		log.Printf("pubkey= %s", hex.EncodeToString(pubkey))
		log.Panic("ERROR: pubkey verification failed, for deterministic. ret=%d", ret)
		return nil
	}

	return pubkey
}
Пример #2
0
// Generate a human readable sha1 hash of the given file path
func hashFile(path string) (hashes FileInfo, err error) {
	f, err := os.Open(path)
	if err != nil {
		return
	}
	defer f.Close()

	reader := bufio.NewReader(f)

	if GetConfig().Hashes.SHA1 {
		sha1Hash := sha1.New()
		_, err = io.Copy(sha1Hash, reader)
		if err == nil {
			hashes.Sha1 = hex.EncodeToString(sha1Hash.Sum(nil))
		}
	}
	if GetConfig().Hashes.SHA256 {
		sha256Hash := sha256.New()
		_, err = io.Copy(sha256Hash, reader)
		if err == nil {
			hashes.Sha256 = hex.EncodeToString(sha256Hash.Sum(nil))
		}
	}
	if GetConfig().Hashes.MD5 {
		md5Hash := md5.New()
		_, err = io.Copy(md5Hash, reader)
		if err == nil {
			hashes.Md5 = hex.EncodeToString(md5Hash.Sum(nil))
		}
	}
	return
}
Пример #3
0
func (socket *mongoSocket) loginClassic(cred Credential) error {
	// Note that this only works properly because this function is
	// synchronous, which means the nonce won't get reset while we're
	// using it and any other login requests will block waiting for a
	// new nonce provided in the defer call below.
	nonce, err := socket.getNonce()
	if err != nil {
		return err
	}
	defer socket.resetNonce()

	psum := md5.New()
	psum.Write([]byte(cred.Username + ":mongo:" + cred.Password))

	ksum := md5.New()
	ksum.Write([]byte(nonce + cred.Username))
	ksum.Write([]byte(hex.EncodeToString(psum.Sum(nil))))

	key := hex.EncodeToString(ksum.Sum(nil))

	cmd := authCmd{Authenticate: 1, User: cred.Username, Nonce: nonce, Key: key}
	res := authResult{}
	return socket.loginRun(cred.Source, &cmd, &res, func() error {
		if !res.Ok {
			return errors.New(res.ErrMsg)
		}
		socket.Lock()
		socket.dropAuth(cred.Source)
		socket.creds = append(socket.creds, cred)
		socket.Unlock()
		return nil
	})
}
Пример #4
0
func (mod *module) introduceVia(router *e3x.Exchange, to hashname.H) error {
	localIdent, err := mod.e.LocalIdentity()
	if err != nil {
		return err
	}

	keys := localIdent.Keys()
	parts := hashname.PartsFromKeys(keys)

	for csid, key := range keys {
		inner := lob.New(key.Public())
		for partCSID, part := range parts {
			if partCSID == csid {
				inner.Header().SetBool(hex.EncodeToString([]byte{partCSID}), true)
			} else {
				inner.Header().SetString(hex.EncodeToString([]byte{partCSID}), part)
			}
		}

		body, err := lob.Encode(inner)
		if err != nil {
			return err
		}

		err = mod.peerVia(router, to, body)
		if err != nil {
			return err
		}
	}

	return nil
}
Пример #5
0
func (c *CoinsDB) Put(utxo bitcoin.Utxo) error {
	c.lock.Lock()
	defer c.lock.Unlock()
	tx, err := c.db.Begin()
	if err != nil {
		return err
	}
	stmt, err := tx.Prepare("insert into coins(outpoint, value, scriptPubKey) values(?,?,?)")
	if err != nil {
		return err
	}
	outpoint := hex.EncodeToString(utxo.Txid) + ":" + strconv.Itoa(utxo.Index)
	defer stmt.Close()
	_, err = stmt.Exec(
		outpoint,
		utxo.Value,
		hex.EncodeToString(utxo.ScriptPubKey),
	)
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}
Пример #6
0
// Response is called by the HTTP server to handle a new OCSP request.
func (src *DBSource) Response(req *ocsp.Request) (response []byte, present bool) {
	log := blog.GetAuditLogger()

	// Check that this request is for the proper CA
	if bytes.Compare(req.IssuerKeyHash, src.caKeyHash) != 0 {
		log.Debug(fmt.Sprintf("Request intended for CA Cert ID: %s", hex.EncodeToString(req.IssuerKeyHash)))
		present = false
		return
	}

	serialString := core.SerialToString(req.SerialNumber)
	log.Debug(fmt.Sprintf("Searching for OCSP issued by us for serial %s", serialString))

	var ocspResponse core.OCSPResponse
	// Note: we order by id rather than createdAt, because otherwise we sometimes
	// get the wrong result if a certificate is revoked in the same second as its
	// last update (e.g. client issues and instant revokes).
	err := src.dbMap.SelectOne(&ocspResponse, "SELECT * from ocspResponses WHERE serial = :serial ORDER BY id DESC LIMIT 1;",
		map[string]interface{}{"serial": serialString})
	if err != nil {
		present = false
		return
	}

	log.Info(fmt.Sprintf("OCSP Response sent for CA=%s, Serial=%s", hex.EncodeToString(src.caKeyHash), serialString))

	response = ocspResponse.Response
	present = true
	return
}
Пример #7
0
func Test_Abnormal_Keys(t *testing.T) {

	for i := 0; i < 32*1024; i++ {

		seed := RandByte(32)

		pubkey1, seckey1 := generateDeterministicKeyPair(seed)

		if seckey1 == nil {
			t.Fail()
		}

		if pubkey1 == nil {
			t.Fail()
		}

		if VerifyPubkey(pubkey1) != 1 {
			seed_hex := hex.EncodeToString(seed)
			seckey_hex := hex.EncodeToString(seckey1)
			log.Printf("seed= %s", seed_hex)
			log.Printf("seckey= %s", seckey_hex)
			t.Errorf("GenerateKeyPair, generates key that fails validation, run=%i", i)
		}
	}
}
Пример #8
0
// The timestamp in hex encoded form.
func (me UUID) String() string {
	return hex.EncodeToString(me[0:4]) + "-" +
		hex.EncodeToString(me[4:6]) + "-" +
		hex.EncodeToString(me[6:8]) + "-" +
		hex.EncodeToString(me[8:10]) + "-" +
		hex.EncodeToString(me[10:16])
}
Пример #9
0
// Convert a hash into a string with hex encoding
func (h *Hash) String() string {
	if h == nil {
		return hex.EncodeToString(nil)
	} else {
		return hex.EncodeToString(h[:])
	}
}
Пример #10
0
func (d *Deb) hashSections() (string, error) {
	h1 := sha1.New()
	h5 := md5.New()
	w := io.MultiWriter(h1, h5)

	_, err := d.f.Seek(0, 0)
	if err != nil {
		return "", &InvalidDeb{d, err}
	}

	s := ""

	rd := ar.NewReader(d.f)
	for {
		h1.Reset()
		h5.Reset()

		hdr, err := rd.Next()
		if err == io.EOF {
			return s, nil
		} else if err != nil {
			return "", &InvalidDeb{d, err}
		}

		_, err = io.Copy(w, rd)
		if err != nil {
			return "", &InvalidDeb{d, err}
		}

		h1x := hex.EncodeToString(h1.Sum(nil))
		h5x := hex.EncodeToString(h5.Sum(nil))
		s += fmt.Sprintf("\t%s %s %d %s\n", h5x, h1x, hdr.Size, hdr.Name)
	}
}
Пример #11
0
func TestJWKSymmetricKey(t *testing.T) {
	sample1 := `{"kty":"oct","alg":"A128KW","k":"GawgguFyGrWKav7AX4VKUg"}`
	sample2 := `{"kty":"oct","k":"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow","kid":"HMAC key used in JWS spec Appendix A.1 example"}`

	var jwk1 JsonWebKey
	json.Unmarshal([]byte(sample1), &jwk1)

	if jwk1.Algorithm != "A128KW" {
		t.Errorf("expected Algorithm to be A128KW, but was '%s'", jwk1.Algorithm)
	}
	expected1 := fromHexBytes("19ac2082e1721ab58a6afec05f854a52")
	if !bytes.Equal(jwk1.Key.([]byte), expected1) {
		t.Errorf("expected Key to be '%s', but was '%s'", hex.EncodeToString(expected1), hex.EncodeToString(jwk1.Key.([]byte)))
	}

	var jwk2 JsonWebKey
	json.Unmarshal([]byte(sample2), &jwk2)

	if jwk2.KeyID != "HMAC key used in JWS spec Appendix A.1 example" {
		t.Errorf("expected KeyID to be 'HMAC key used in JWS spec Appendix A.1 example', but was '%s'", jwk2.KeyID)
	}
	expected2 := fromHexBytes(`
    0323354b2b0fa5bc837e0665777ba68f5ab328e6f054c928a90f84b2d2502ebf
    d3fb5a92d20647ef968ab4c377623d223d2e2172052e4f08c0cd9af567d080a3`)
	if !bytes.Equal(jwk2.Key.([]byte), expected2) {
		t.Errorf("expected Key to be '%s', but was '%s'", hex.EncodeToString(expected2), hex.EncodeToString(jwk2.Key.([]byte)))
	}
}
Пример #12
0
func (s *SignupJoinEngine) Post(arg SignupJoinEngineRunArg) (err error) {
	var res *libkb.APIRes
	var ppGenTmp int
	res, err = s.G().API.Post(libkb.APIArg{
		Endpoint: "signup",
		Args: libkb.HTTPArgs{
			"salt":          libkb.S{Val: hex.EncodeToString(arg.PWSalt)},
			"pwh":           libkb.S{Val: hex.EncodeToString(arg.PWHash)},
			"username":      libkb.S{Val: arg.Username},
			"email":         libkb.S{Val: arg.Email},
			"invitation_id": libkb.S{Val: arg.InviteCode},
			"pwh_version":   libkb.I{Val: int(triplesec.Version)},
			"skip_mail":     libkb.B{Val: arg.SkipMail},
		}})
	if err == nil {
		s.username = libkb.NewNormalizedUsername(arg.Username)
		libkb.GetUIDVoid(res.Body.AtKey("uid"), &s.uid, &err)
		res.Body.AtKey("session").GetStringVoid(&s.session, &err)
		res.Body.AtKey("csrf_token").GetStringVoid(&s.csrf, &err)
		res.Body.AtPath("me.basics.passphrase_generation").GetIntVoid(&ppGenTmp, &err)
	}
	if err == nil {
		err = libkb.CheckUIDAgainstUsername(s.uid, arg.Username)
		s.ppGen = libkb.PassphraseGeneration(ppGenTmp)
	}
	return
}
Пример #13
0
// Tested functions:
//   EncodedBytesToBigInt
//   BigIntToFieldElement
//   FieldElementToEncodedBytes
//   BigIntToEncodedBytes
//   FieldElementToBigInt
//   EncodedBytesToFieldElement
func TestConversion(t *testing.T) {
	for _, vector := range testConversionVectors() {
		// Test encoding to FE --> bytes.
		feFB := EncodedBytesToFieldElement(vector.bIn)
		feTB := FieldElementToEncodedBytes(feFB)
		assert.Equal(t, vector.bIn, feTB)

		// Test encoding to big int --> FE --> bytes.
		big := EncodedBytesToBigInt(vector.bIn)
		fe := BigIntToFieldElement(big)
		b := FieldElementToEncodedBytes(fe)
		assert.Equal(t, vector.bIn, b)

		// Test encoding to big int --> bytes.
		b = BigIntToEncodedBytes(big)
		assert.Equal(t, vector.bIn, b)

		// Test encoding FE --> big int --> bytes.
		feBig := FieldElementToBigInt(fe)
		b = BigIntToEncodedBytes(feBig)
		assert.Equal(t, vector.bIn, b)

		// Test python lib bytes --> int vs our results.
		args := []string{"testdata/decodeint.py", hex.EncodeToString(vector.bIn[:])}
		pyNumStr, _ := exec.Command("python", args...).Output()
		stripped := strings.TrimSpace(string(pyNumStr))
		assert.Equal(t, stripped, big.String())

		// Test python lib int --> bytes versus our results.
		args = []string{"testdata/encodeint.py", big.String()}
		pyHexStr, _ := exec.Command("python", args...).Output()
		stripped = strings.TrimSpace(string(pyHexStr))
		assert.Equal(t, hex.EncodeToString(vector.bIn[:]), string(stripped))
	}
}
Пример #14
0
// Tested functions:
//   BigIntPointToEncodedBytes
//   extendedToBigAffine
//   EncodedBytesToBigIntPoint
func TestPointConversion(t *testing.T) {
	curve := new(TwistedEdwardsCurve)
	curve.InitParam25519()

	for _, vector := range testPointConversionVectors() {
		x, y, err := curve.EncodedBytesToBigIntPoint(vector.bIn)
		// The random point wasn't on the curve.
		if err != nil {
			continue
		}

		yB := BigIntPointToEncodedBytes(x, y)
		assert.Equal(t, vector.bIn, yB)

		// Test python lib bytes --> point vs our results.
		args := []string{"testdata/decodepoint.py", hex.EncodeToString(vector.bIn[:])}
		pyNumStr, _ := exec.Command("python", args...).Output()
		stripped := strings.TrimSpace(string(pyNumStr))
		var buffer bytes.Buffer
		buffer.WriteString(x.String())
		buffer.WriteString(",")
		buffer.WriteString(y.String())
		localStr := buffer.String()
		assert.Equal(t, localStr, stripped)

		// Test python lib point --> bytes versus our results.
		args = []string{"testdata/encodepoint.py", x.String(), y.String()}
		pyHexStr, _ := exec.Command("python", args...).Output()
		stripped = strings.TrimSpace(string(pyHexStr))
		assert.Equal(t, hex.EncodeToString(vector.bIn[:]), string(stripped))
	}
}
Пример #15
0
func (o arc4Verifier) validate(count string, offset uint64, key, plaintext, expectedCiphertext []byte) {
	if offset%16 != 0 || len(plaintext) != 16 || len(expectedCiphertext) != 16 {
		panic(fmt.Errorf("Unexpected input value encountered: offset=%v; len(plaintext)=%v; len(expectedCiphertext)=%v",
			offset,
			len(plaintext),
			len(expectedCiphertext)))
	}
	stream, err := rc4.NewCipher(key)
	if err != nil {
		panic(err)
	}

	var currentOffset uint64 = 0
	ciphertext := make([]byte, len(plaintext))
	for currentOffset <= offset {
		stream.XORKeyStream(ciphertext, plaintext)
		currentOffset += uint64(len(plaintext))
	}
	if !bytes.Equal(ciphertext, expectedCiphertext) {
		panic(fmt.Errorf("vector mismatch @ COUNT = %s:\n  %s != %s\n",
			count,
			hex.EncodeToString(expectedCiphertext),
			hex.EncodeToString(ciphertext)))
	}
}
Пример #16
0
// Print outputs a formatted dump of the RTP packet.
func (rp *DataPacket) Print(label string) {
	fmt.Printf("RTP Packet at: %s\n", label)
	fmt.Printf("  fixed header dump:   %s\n", hex.EncodeToString(rp.buffer[0:rtpHeaderLength]))
	fmt.Printf("    Version:           %d\n", (rp.buffer[0]&0xc0)>>6)
	fmt.Printf("    Padding:           %t\n", rp.Padding())
	fmt.Printf("    Extension:         %t\n", rp.ExtensionBit())
	fmt.Printf("    Contributing SRCs: %d\n", rp.CsrcCount())
	fmt.Printf("    Marker:            %t\n", rp.Marker())
	fmt.Printf("    Payload type:      %d (0x%x)\n", rp.PayloadType(), rp.PayloadType())
	fmt.Printf("    Sequence number:   %d (0x%x)\n", rp.Sequence(), rp.Sequence())
	fmt.Printf("    Timestamp:         %d (0x%x)\n", rp.Timestamp(), rp.Timestamp())
	fmt.Printf("    SSRC:              %d (0x%x)\n", rp.Ssrc(), rp.Ssrc())

	if rp.CsrcCount() > 0 {
		cscr := rp.CsrcList()
		fmt.Printf("  CSRC list:\n")
		for i, v := range cscr {
			fmt.Printf("      %d: %d (0x%x)\n", i, v, v)
		}
	}
	if rp.ExtensionBit() {
		extLen := rp.ExtensionLength()
		fmt.Printf("  Extentsion length: %d\n", extLen)
		offsetExt := rtpHeaderLength + int(rp.CsrcCount()*4)
		fmt.Printf("    extension: %s\n", hex.EncodeToString(rp.buffer[offsetExt:offsetExt+extLen]))
	}
	payOffset := rtpHeaderLength + int(rp.CsrcCount()*4) + rp.ExtensionLength()
	fmt.Printf("  payload: %s\n", hex.EncodeToString(rp.buffer[payOffset:rp.inUse]))
}
Пример #17
0
func (s *ParseMessageTestSuite) TestParseTextAttachment() {
	loop := 1
	for i := 0; i < loop; i++ {
		fileHandler, err := os.Open("fixtures/text_attachment.eml")
		assert.Nil(s.T(), err)

		reader := bufio.NewReader(fileHandler)
		parse := NewParse(reader)
		assert.Equal(s.T(), parse.To(), "Team R&D <*****@*****.**>")
		hasher := md5.New()

		text, _ := parse.Text()
		hasher.Write([]byte(text))
		hashString := hex.EncodeToString(hasher.Sum(nil))
		assert.Equal(s.T(), hashString, "b5b94cd495174ab6e4443fa81847b6ce")
		hasher.Reset()

		html, _ := parse.Html()
		hasher.Write([]byte(html))
		hashString = hex.EncodeToString(hasher.Sum(nil))
		assert.Equal(s.T(), hashString, "d41d8cd98f00b204e9800998ecf8427e")
		hasher.Reset()

		attachments := parse.Attachment()
		for key, value := range attachments {
			assert.Equal(s.T(), key, "content-type-sorted-distilled.txt")

			hasher.Write(value)
			hashString = hex.EncodeToString(hasher.Sum(nil))
			assert.Equal(s.T(), hashString, "bcd2881b9b06f24960d4998567be37bd")
			hasher.Reset()
		}
		fileHandler.Close()
	}
}
Пример #18
0
// Response is called by the HTTP server to handle a new OCSP request.
func (src *DBSource) Response(req *ocsp.Request) ([]byte, bool) {
	// Check that this request is for the proper CA
	if bytes.Compare(req.IssuerKeyHash, src.caKeyHash) != 0 {
		src.log.Debug(fmt.Sprintf("Request intended for CA Cert ID: %s", hex.EncodeToString(req.IssuerKeyHash)))
		return nil, false
	}

	serialString := core.SerialToString(req.SerialNumber)
	src.log.Debug(fmt.Sprintf("Searching for OCSP issued by us for serial %s", serialString))

	var response []byte
	defer func() {
		if len(response) != 0 {
			src.log.Info(fmt.Sprintf("OCSP Response sent for CA=%s, Serial=%s", hex.EncodeToString(src.caKeyHash), serialString))
		}
	}()
	err := src.dbMap.SelectOne(
		&response,
		"SELECT ocspResponse FROM certificateStatus WHERE serial = :serial",
		map[string]interface{}{"serial": serialString},
	)
	if err != nil && err != sql.ErrNoRows {
		src.log.Err(fmt.Sprintf("Failed to retrieve response from certificateStatus table: %s", err))
	}
	if err != nil {
		return nil, false
	}

	return response, true
}
Пример #19
0
func main() {
	fmt.Printf("Login......\n")
	unixTime := getUnixTime()

	//*******************token process begin************************
	var orignalToken = getToken(unixTime)
	//fmt.Printf("%s \n",orignalToken)
	vm.Set("token", orignalToken)
	token, error := vm.Run(encyptFunctions)
	if error != nil {
		//handler error
	}
	md5_t := md5.New()
	s_token, error := token.ToString()
	if error != nil {
		//handler error
	}
	md5_t.Write([]byte(s_token))
	true_token := hex.EncodeToString(md5_t.Sum(nil))
	//*******************token process end************************

	time.Sleep(1 * time.Second)
	email := "" //your email
	pwd := ""   //your password
	md5_p := md5.New()
	md5_p.Write([]byte(pwd))
	passwd := hex.EncodeToString(md5_p.Sum(nil))

	result := login(true_token, unixTime, email, passwd)
	fmt.Printf("%s\n", result)
}
Пример #20
0
// add P2SH pre-signing data into a raw tx
func make_p2sh() {
	tx := raw_tx_from_file(*rawtx)
	if tx == nil {
		fmt.Println("ERROR: Cannot decode the raw transaction")
		return
	}

	d, er := hex.DecodeString(*p2sh)
	if er != nil {
		println("P2SH hex data:", er.Error())
		return
	}

	ms, er := btc.NewMultiSigFromP2SH(d)
	if er != nil {
		println("Decode P2SH:", er.Error())
		return
	}

	fmt.Println("The P2SH data points to address", ms.BtcAddr(testnet).String())

	sd := ms.Bytes()

	for i := range tx.TxIn {
		tx.TxIn[i].ScriptSig = sd
		fmt.Println("Input number", i, " - hash to sign:", hex.EncodeToString(tx.SignatureHash(d, i, btc.SIGHASH_ALL)))
	}
	ioutil.WriteFile(MultiToSignOut, []byte(hex.EncodeToString(tx.Serialize())), 0666)
	fmt.Println("Transaction with", len(tx.TxIn), "inputs ready for multi-signing, stored in", MultiToSignOut)
}
Пример #21
0
func TestAddPoliciesWithQualifiers(t *testing.T) {
	var cert x509.Certificate
	addPolicies(&cert, []config.CertificatePolicy{
		config.CertificatePolicy{
			ID: config.OID{1, 2, 3, 4},
			Qualifiers: []config.CertificatePolicyQualifier{
				config.CertificatePolicyQualifier{
					Type:  "id-qt-cps",
					Value: "http://example.com/cps",
				},
				config.CertificatePolicyQualifier{
					Type:  "id-qt-unotice",
					Value: "Do What Thou Wilt",
				},
			},
		},
	})

	if len(cert.ExtraExtensions) != 1 {
		t.Fatal("No extension added")
	}
	ext := cert.ExtraExtensions[0]
	if !reflect.DeepEqual(ext.Id, asn1.ObjectIdentifier{2, 5, 29, 32}) {
		t.Fatal(fmt.Sprintf("Wrong OID for policy qualifier %v", ext.Id))
	}
	if ext.Critical {
		t.Fatal("Policy qualifier marked critical")
	}
	expectedBytes, _ := hex.DecodeString("304e304c06032a03043045302206082b060105050702011616687474703a2f2f6578616d706c652e636f6d2f637073301f06082b0601050507020230130c11446f20576861742054686f752057696c74")
	if !bytes.Equal(ext.Value, expectedBytes) {
		t.Fatal(fmt.Sprintf("Value didn't match expected bytes: %s vs %s",
			hex.EncodeToString(ext.Value), hex.EncodeToString(expectedBytes)))
	}
}
Пример #22
0
// Print all the piblic addresses
func dump_addrs() {
	f, _ := os.Create("wallet.txt")

	fmt.Fprintln(f, "# Deterministic Walet Type", *waltype)
	if type2_secret != nil {
		fmt.Fprintln(f, "#", hex.EncodeToString(publ_addrs[0].Pubkey))
		fmt.Fprintln(f, "#", hex.EncodeToString(type2_secret.Bytes()))
	}
	for i := range publ_addrs {
		if !*noverify {
			if er := btc.VerifyKeyPair(priv_keys[i], publ_addrs[i].Pubkey); er != nil {
				println("Something wrong with key at index", i, " - abort!", er.Error())
				os.Exit(1)
			}
		}
		fmt.Println(publ_addrs[i].String(), labels[i])
		if f != nil {
			fmt.Fprintln(f, publ_addrs[i].String(), labels[i])
		}
	}
	if f != nil {
		f.Close()
		fmt.Println("You can find all the addresses in wallet.txt file")
	}
}
Пример #23
0
func (kvb *kvBatch) IndexRom(rom *types.Rom) error {
	glog.V(4).Infof("indexing rom %s", rom.Name)

	if rom.Sha1 != nil {
		if rom.Crc != nil {
			glog.V(4).Infof("declaring crc %s -> sha1 %s mapping", hex.EncodeToString(rom.Crc), hex.EncodeToString(rom.Sha1))
			err := kvb.crcsha1Batch.Set(rom.CrcWithSizeAndSha1Key(nil), oneValue)
			if err != nil {
				return err
			}
			kvb.size += int64(sha1.Size)
		}
		if rom.Md5 != nil {
			glog.V(4).Infof("declaring md5 %s -> sha1 %s mapping", hex.EncodeToString(rom.Md5), hex.EncodeToString(rom.Sha1))
			err := kvb.md5sha1Batch.Set(rom.Md5WithSizeAndSha1Key(nil), oneValue)
			if err != nil {
				return err
			}
			kvb.size += int64(sha1.Size)
		}
	} else {
		glog.V(4).Infof("indexing rom %s with missing SHA1", rom.Name)
	}

	return nil
}
Пример #24
0
// Create a new encryption key and encrypt it using the user-provided
// passphrase. Prints output to stdout that gives text to add to the
// ~/.skicka.config file to store the encryption key.
func generateKey() {
	passphrase := os.Getenv(passphraseEnvironmentVariable)
	if passphrase == "" {
		printErrorAndExit(fmt.Errorf(passphraseEnvironmentVariable +
			" environment variable not set."))
	}

	// Derive a 64-byte hash from the passphrase using PBKDF2 with 65536
	// rounds of SHA256.
	salt := getRandomBytes(32)
	hash := pbkdf2.Key([]byte(passphrase), salt, 65536, 64, sha256.New)
	if len(hash) != 64 {
		printErrorAndExit(fmt.Errorf("incorrect key size returned by pbkdf2 %d", len(hash)))
	}

	// We'll store the first 32 bytes of the hash to use to confirm the
	// correct passphrase is given on subsequent runs.
	passHash := hash[:32]
	// And we'll use the remaining 32 bytes as a key to encrypt the actual
	// encryption key. (These bytes are *not* stored).
	keyEncryptKey := hash[32:]

	// Generate a random encryption key and encrypt it using the key
	// derived from the passphrase.
	key := getRandomBytes(32)
	iv := getRandomBytes(16)
	encryptedKey := encryptBytes(keyEncryptKey, iv, key)

	fmt.Printf("; Add the following lines to the [encryption] section\n")
	fmt.Printf("; of your ~/.skicka.config file.\n")
	fmt.Printf("\tsalt=%s\n", hex.EncodeToString(salt))
	fmt.Printf("\tpassphrase-hash=%s\n", hex.EncodeToString(passHash))
	fmt.Printf("\tencrypted-key=%s\n", hex.EncodeToString(encryptedKey))
	fmt.Printf("\tencrypted-key-iv=%s\n", hex.EncodeToString(iv))
}
Пример #25
0
// Response is called by the HTTP server to handle a new OCSP request.
func (src *DBSource) Response(req *ocsp.Request) (response []byte, present bool) {
	log := blog.GetAuditLogger()

	// Check that this request is for the proper CA
	if bytes.Compare(req.IssuerKeyHash, src.caKeyHash) != 0 {
		log.Debug(fmt.Sprintf("Request intended for CA Cert ID: %s", hex.EncodeToString(req.IssuerKeyHash)))
		present = false
		return
	}

	serialString := core.SerialToString(req.SerialNumber)
	log.Debug(fmt.Sprintf("Searching for OCSP issued by us for serial %s", serialString))

	var ocspResponse core.OCSPResponse
	err := src.dbMap.SelectOne(&ocspResponse, "SELECT * from ocspResponses WHERE serial = :serial  ORDER BY createdAt DESC LIMIT 1;",
		map[string]interface{}{"serial": serialString})
	if err != nil {
		present = false
		return
	}

	log.Info(fmt.Sprintf("OCSP Response sent for CA=%s, Serial=%s", hex.EncodeToString(src.caKeyHash), serialString))

	response = ocspResponse.Response
	present = true
	return
}
Пример #26
0
Файл: td4.go Проект: silky/rct
func readRaptor() Ride {
	encodedBits, err := ioutil.ReadFile("rides/raptor.td4")
	if err != nil {
		panic(err)
	}
	z := rle.NewReader(bytes.NewReader(encodedBits))
	if err != nil {
		panic(err)
	}
	var bitbuffer bytes.Buffer
	bitbuffer.ReadFrom(z)
	decrypted := bitbuffer.Bytes()
	for i := 0; i < 40; i++ {
		// encode the value of i as hex
		ds := hex.EncodeToString([]byte{byte(i)})
		bitValueInHex := hex.EncodeToString([]byte{decrypted[i]})
		fmt.Printf("%s: %s\n", ds, bitValueInHex)
	}

	// r is a pointer
	r := new(Ride)
	Unmarshal(decrypted, r)
	bits, err := Marshal(r)
	fmt.Println(bits)
	return *r
}
Пример #27
0
// test create object
func (s *MyCacheSuite) TestNewObjectCanBeWritten(c *C) {
	err := dc.MakeBucket("foo", "private", nil, nil)
	c.Assert(err, IsNil)

	data := "Hello World"

	hasher := md5.New()
	hasher.Write([]byte(data))
	expectedMd5Sum := base64.StdEncoding.EncodeToString(hasher.Sum(nil))
	reader := ioutil.NopCloser(bytes.NewReader([]byte(data)))

	actualMetadata, err := dc.CreateObject("foo", "obj", expectedMd5Sum, int64(len(data)), reader, map[string]string{"contentType": "application/octet-stream"}, nil)
	c.Assert(err, IsNil)
	c.Assert(actualMetadata.MD5Sum, Equals, hex.EncodeToString(hasher.Sum(nil)))

	var buffer bytes.Buffer
	size, err := dc.GetObject(&buffer, "foo", "obj", 0, 0)
	c.Assert(err, IsNil)
	c.Assert(size, Equals, int64(len(data)))
	c.Assert(buffer.Bytes(), DeepEquals, []byte(data))

	actualMetadata, err = dc.GetObjectMetadata("foo", "obj", nil)
	c.Assert(err, IsNil)
	c.Assert(hex.EncodeToString(hasher.Sum(nil)), Equals, actualMetadata.MD5Sum)
	c.Assert(int64(len(data)), Equals, actualMetadata.Size)
}
Пример #28
0
func handleEntry(ctx *web.Context, hash string) {
	type entry struct {
		ChainID string
		Content string
		ExtIDs  []string
	}

	e := new(entry)
	if entry, err := factomapi.EntryByHash(hash); err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	} else {
		e.ChainID = entry.ChainID.String()
		e.Content = hex.EncodeToString(entry.Content)
		for _, v := range entry.ExtIDs {
			e.ExtIDs = append(e.ExtIDs, hex.EncodeToString(v))
		}
	}

	if p, err := json.Marshal(e); err != nil {
		wsLog.Error(err)
		ctx.WriteHeader(httpBad)
		ctx.Write([]byte(err.Error()))
		return
	} else {
		ctx.Write(p)
	}
}
Пример #29
0
func GetMember(email, password string) (Member, error) {
	log.Printf("Get member '%s' ('%s')", email, password)
	db, err := GetDBConnection()
	if err == nil {
		defer db.Close()
		pwd := sha256.Sum256([]byte(password))
		log.Printf("Encrypted password: %s", hex.EncodeToString(pwd[:]))
		row := db.QueryRow(`SELECT id, email, first_name
			FROM Member
			WHERE email = $1 AND password = $2`,
			email,
			hex.EncodeToString(pwd[:]),
		)
		result := Member{}
		err = row.Scan(&result.id, &result.email, &result.firstName)
		log.Printf("Err: %v", err)
		if err == nil {
			return result, nil
		} else {
			return result, errors.New("Unable to find Member with email: " + email)
		}
	} else {
		return Member{}, errors.New("Unable to get database connection")
	}
}
Пример #30
0
// reads the configuration file from the path specified by
// the config command line flag.
func readConfig(configFile string) error {
	b, err := ioutil.ReadFile(configFile)
	if err != nil {
		return err
	}
	err = json.Unmarshal(b, &config)
	if err != nil {
		return err
	}
	cookieAuthKey, err = hex.DecodeString(*config.CookieAuthKeyHexStr)
	if err != nil {
		return err
	}
	cookieEncrKey, err = hex.DecodeString(*config.CookieEncrKeyHexStr)
	if err != nil {
		return err
	}
	secureCookie = securecookie.New(cookieAuthKey, cookieEncrKey)
	// verify auth/encr keys are correct
	val := map[string]string{
		"foo": "bar",
	}
	_, err = secureCookie.Encode(cookieName, val)
	if err != nil {
		// for convenience, if the auth/encr keys are not set,
		// generate valid, random value for them
		auth := securecookie.GenerateRandomKey(32)
		encr := securecookie.GenerateRandomKey(32)
		fmt.Printf("auth: %s\nencr: %s\n", hex.EncodeToString(auth), hex.EncodeToString(encr))
	}
	// TODO: somehow verify twitter creds
	return err
}