Esempio n. 1
0
func BenchmarkPe1bloop(b *testing.B) {
	bi := new(big.Int)
	bi.SetUint64(uint64(1000000))
	for i := 0; i < b.N; i++ {
		pe.Pe1bloop(bi)
	}
}
Esempio n. 2
0
func TestDecodeBigNumber(t *testing.T) {
	var value big.Int

	value.SetUint64(^uint64(0))

	value.Mul(&value, big.NewInt(32))

	b := bytes.Buffer{}
	e := NewEncoder(&b)

	err := e.Encode(value)
	if err != nil {
		t.Fatal(err)
	}

	t.Log(hex.Dump(b.Bytes()))

	d := NewDecoder(&b)

	found, err := d.DecodeNext()
	if err != nil {
		t.Fatal(err)
	}
	i := found.(big.Int)

	if i.Cmp(&value) != 0 {
		t.Fatalf("expected %v but %v found", value, found)
	}
}
Esempio n. 3
0
func calcDifficultyFrontier(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
	diff := new(big.Int)
	adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
	bigTime := new(big.Int)
	bigParentTime := new(big.Int)

	bigTime.SetUint64(time)
	bigParentTime.SetUint64(parentTime)

	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
		diff.Add(parentDiff, adjust)
	} else {
		diff.Sub(parentDiff, adjust)
	}
	if diff.Cmp(params.MinimumDifficulty) < 0 {
		diff.Set(params.MinimumDifficulty)
	}

	periodCount := new(big.Int).Add(parentNumber, common.Big1)
	periodCount.Div(periodCount, ExpDiffPeriod)
	if periodCount.Cmp(common.Big1) > 0 {
		// diff = diff + 2^(periodCount - 2)
		expDiff := periodCount.Sub(periodCount, common.Big2)
		expDiff.Exp(common.Big2, expDiff, nil)
		diff.Add(diff, expDiff)
		diff = common.BigMax(diff, params.MinimumDifficulty)
	}

	return diff
}
Esempio n. 4
0
// "stolen" from https://golang.org/pkg/math/big/#Rat.SetFloat64
// Removed non-finite case because we already check for
// Inf/NaN values
func bigIntFromFloat(f float64) *big.Int {
	const expMask = 1<<11 - 1
	bits := math.Float64bits(f)
	mantissa := bits & (1<<52 - 1)
	exp := int((bits >> 52) & expMask)
	if exp == 0 { // denormal
		exp -= 1022
	} else { // normal
		mantissa |= 1 << 52
		exp -= 1023
	}

	shift := 52 - exp

	// Optimization (?): partially pre-normalise.
	for mantissa&1 == 0 && shift > 0 {
		mantissa >>= 1
		shift--
	}

	if shift < 0 {
		shift = -shift
	}

	var a big.Int
	a.SetUint64(mantissa)
	return a.Lsh(&a, uint(shift))
}
Esempio n. 5
0
func (m *Material) Info() [][][2]string {
	var info [][][2]string

	maybe := func(name string, stat world.Stat) {
		var total, volume, tmp big.Int
		for _, c := range m.components {
			tmp.SetUint64(c.volume)
			volume.Add(&volume, &tmp)
			total.Add(&total, tmp.Mul(c.data().Stat(stat), &tmp))
		}
		if volume.Sign() == 0 {
			return
		}
		total.Div(tmp.Mul(&total, &m.quality), &volume)
		switch total.Sign() {
		case 0:
			return
		case 1:
			info = append(info, [][2]string{
				{"+" + Comma(&total), "#4f4"},
				{name, "#ccc"},
			})
		case -1:
			info = append(info, [][2]string{
				{Comma(&total), "#f44"},
				{name, "#ccc"},
			})
		}
	}

	maybe(" power", world.StatPower)
	maybe(" magic", world.StatMagic)
	maybe(" agility", world.StatAgility)
	maybe(" luck", world.StatLuck)
	maybe(" intelligence", world.StatIntelligence)
	maybe(" stamina", world.StatStamina)
	maybe(" integrity", world.StatIntegrity)

	maybe(" melee damage", world.StatMeleeDamage)
	maybe(" magic damage", world.StatMagicDamage)
	maybe(" mana", world.StatMana)
	maybe(" mana regen", world.StatManaRegen)
	maybe(" crit chance", world.StatCritChance)
	maybe(" attack speed", world.StatAttackSpeed)

	maybe(" melee armor", world.StatMeleeArmor)
	maybe(" magic armor", world.StatMagicArmor)
	maybe(" health", world.StatHealth)
	maybe(" health regen", world.StatHealthRegen)
	maybe(" resistance", world.StatResistance)
	maybe(" movement speed", world.StatMovementSpeed)

	maybe(" gathering", world.StatGathering)
	maybe(" structure health", world.StatStructureHealth)

	return info
}
Esempio n. 6
0
func TestPe1bloop(t *testing.T) {
	bi := new(big.Int)
	bi.SetUint64(uint64(1000))

	actual := pe.Pe1bloop(bi)
	expected := new(big.Int).SetUint64(uint64(234168))

	if actual.Cmp(expected) != 0 {
		t.Errorf("got %v, want %v", actual, expected)
	}
}
Esempio n. 7
0
// computeChildSecret helper method that derives a child secret key from the
// intermediary state.
func (k *HDKey) computeChildSecret(ilInt *big.Int) *eckey.SecretKey {
	keyInt := new(big.Int).SetBytes(k[childKeyOffset+1:])
	defer keyInt.SetUint64(0)

	ilInt.Add(ilInt, keyInt)
	ilInt.Mod(ilInt, eckey.S256.N)

	sk := new(eckey.SecretKey)
	util.PaddedCopy(sk[:], ilInt.Bytes(), eckey.SecretSize)

	return sk
}
Esempio n. 8
0
// Child computes the descendant of an HDKey at the specified child number.
func (k *HDKey) Child(i uint32) (*HDKey, error) {
	// Verify that child derivation is possible
	isChildHardened := i >= HardenedKeyStart
	if !k.IsPrivate() && isChildHardened {
		return nil, ErrDeriveHardenedFromPublic
	}

	// Assemble seed data for HMAC
	seed := make([]byte, childKeySize+childNumberSize)
	if isChildHardened {
		copy(seed, k[childKeyOffset:]) // Copy 0x00 || 32-byte secret key
	} else {
		copy(seed, k.CompressedPublicKey()[:]) // Copy HEADER || 32-byte X-coord
	}
	// Copy child number as uint32
	binary.BigEndian.PutUint32(seed[childKeySize:], i)

	// il, ir = HMAC-512(chainCode, seed), clean up intermediary state
	il, childChainCode := util.HMAC512Split(k.chainCode(), seed)
	defer func() { util.Zero(il); util.Zero(childChainCode) }()

	// Left 32 bytes becomes intermediate secret key, defer clean up
	ilInt := new(big.Int).SetBytes(il)
	defer ilInt.SetUint64(0)

	// Check that ilInt creates valid SecretKey, clean up intermediary SecretKey
	isk, err := eckey.NewSecretKeyInt(ilInt)
	if err != nil {
		return nil, ErrUnusableSeed
	}
	defer isk.Zero()

	ver := k.version()
	parentCPK := k.CompressedPublicKey()
	fpBytes := util.Hash256d(parentCPK[:])[:fingerprintSize]
	fp := binary.BigEndian.Uint32(fpBytes)

	// If key is private, derive a child secret key
	if k.IsPrivate() {
		sk := k.computeChildSecret(ilInt)
		return newHDSecretKey(ver, k.depth()+1, fp, i, childChainCode, sk), nil
	}

	// Otherwise, derive child public key
	cpk, err := computeChildPublic(parentCPK, isk)
	if err != nil {
		return nil, err
	}

	return newHDPublicKey(ver, k.depth()+1, fp, i, childChainCode, cpk), nil
}
Esempio n. 9
0
func TestModSqr(t *testing.T) {
	A := new(big.Int)
	B := new(big.Int)
	for _, a := range numbers {
		A.SetUint64(a)
		b := mod_sqr(a)
		B.Mul(A, A)
		B.Mod(B, P)
		expected := B.Uint64()
		if b != expected {
			t.Fatalf("%d**2: Expecting %d but got %d", a, expected, b)
		}
	}
}
Esempio n. 10
0
func pe1b() {
	bi := new(big.Int)
	if len(os.Args) > 1 {
		if _, ok := bi.SetString(os.Args[1], 10); !ok {
			fmt.Printf("couldn't interpret line %#v\n", os.Args[1])
		}
	} else {
		bi.SetUint64(uint64(1000))
	}

	//ans := pe.Pe1bloop(bi)
	ans := pe.Pe1b(bi)
	fmt.Println("pe1: ", ans)
}
Esempio n. 11
0
func (m *Material) stat(stat, meta *world.Stat) *big.Int {
	var total, volume, tmp big.Int
	for _, c := range m.components {
		tmp.SetUint64(c.volume)
		volume.Add(&volume, &tmp)
		total.Add(&total, tmp.Mul(c.data().Stat(*stat), &tmp))
		if meta != nil {
			total.Add(&total, tmp.Div(tmp.Mul(c.data().Stat(*meta), tmp.SetUint64(c.volume)), world.TuningMetaStatDivisor))
		}
	}
	if volume.Sign() == 0 {
		return &volume
	}
	total.Div(tmp.Mul(&total, &m.quality), &volume)
	return &total
}
Esempio n. 12
0
func NewSecretKey(b []byte) (*SecretKey, error) {
	if len(b) != SecretSize {
		return nil, ErrInvalidSecretLength
	}

	// Copy secret bytes and clean up
	s := new(big.Int).SetBytes(b)
	defer s.SetUint64(0)

	sk, err := NewSecretKeyInt(s)
	if err != nil {
		return nil, err
	}

	return sk, nil
}
Esempio n. 13
0
func TestModInv(t *testing.T) {
	A := new(big.Int)
	B := new(big.Int)
	for _, a := range numbers {
		if a == 0 {
			continue
		}
		A.SetUint64(a)
		b := mod_inv(a)
		B.ModInverse(A, P)
		expected := B.Uint64()
		if b != expected {
			t.Fatalf("inv(%d): Expecting %d but got %d", a, expected, b)
		}
	}
}
Esempio n. 14
0
func TestModShift(t *testing.T) {
	A := new(big.Int)
	C := new(big.Int)
	for _, a := range numbers {
		A.SetUint64(a)
		for b := uint8(0); b < 96; b++ {
			c := mod_shift(a, b)
			C.Lsh(A, uint(b))
			C.Mod(C, P)
			expected := C.Uint64()
			if c != expected {
				t.Fatalf("%d << %d: Expecting %d but got %d", a, b, expected, c)
			}
		}
	}
}
Esempio n. 15
0
func TestModPow(t *testing.T) {
	A := new(big.Int)
	B := new(big.Int)
	C := new(big.Int)
	for _, a := range numbers {
		A.SetUint64(a)
		for _, b := range numbers {
			B.SetUint64(b)
			c := mod_pow(a, b)
			C.Exp(A, B, P)
			expected := C.Uint64()
			if c != expected {
				t.Errorf("0x%X ** 0x%X: Expecting 0x%X but got 0x%X", a, b, expected, c)
			}
		}
	}
}
Esempio n. 16
0
func TestModAdd(t *testing.T) {
	A := new(big.Int)
	B := new(big.Int)
	C := new(big.Int)
	for _, a := range numbers {
		A.SetUint64(a)
		for _, b := range numbers {
			B.SetUint64(b)
			c := mod_add(a, b)
			C.Add(A, B)
			C.Mod(C, P)
			expected := C.Uint64()
			if c != expected {
				t.Fatalf("%d + %d: Expecting %d but got %d", a, b, expected, c)
			}
		}
	}
}
Esempio n. 17
0
func DecodeAlphabet(alphabet []byte, s string) []byte {
	multiplier := big.NewInt(1)
	base := big.NewInt(int64(len(alphabet)))
	total := big.NewInt(0)
	value := new(big.Int)

	for i := 0; i < len(s); i++ {
		n := bytes.Index(alphabet, []byte(s[i:i+1]))

		value.SetUint64(uint64(n))

		value.Mul(value, multiplier)
		multiplier.Mul(multiplier, base)

		total.Add(total, value)
	}

	return total.Bytes()
}
Esempio n. 18
0
// CalcDifficulty is the difficulty adjustment algorithm. It returns
// the difficulty that a new block b should have when created at time
// given the parent block's time and difficulty.
func CalcDifficulty(time, parentTime uint64, parentDiff *big.Int) *big.Int {
	diff := new(big.Int)
	adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
	bigTime := new(big.Int)
	bigParentTime := new(big.Int)

	bigTime.SetUint64(time)
	bigParentTime.SetUint64(parentTime)

	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
		diff.Add(parentDiff, adjust)
	} else {
		diff.Sub(parentDiff, adjust)
	}
	if diff.Cmp(params.MinimumDifficulty) < 0 {
		return params.MinimumDifficulty
	}
	return diff
}
Esempio n. 19
0
func TestModReduce(t *testing.T) {
	MakeNumbers()
	A := new(big.Int)
	B := new(big.Int)
	C := new(big.Int)
	for _, a := range numbers {
		A.SetUint64(a)
		for _, b := range numbers {
			B.SetUint64(b)
			c := mod_reduce(a, b)
			C.Lsh(A, 64)
			C.Add(C, B)
			C.Mod(C, P)
			expected := C.Uint64()
			if c != expected {
				t.Fatalf("mod_reduce(%d,%d): Expecting %d but got %d", a, b, expected, c)
			}
		}
	}
}
Esempio n. 20
0
func TestModAdc(t *testing.T) {
	A := new(big.Int)
	B := new(big.Int)
	C := new(big.Int)
	Carry := new(big.Int)
	Mask := new(big.Int)
	for _, a := range numbers {
		A.SetUint64(a)
		for _, b := range numbers {
			B.SetUint64(b)
			for width := uint8(1); width < 64; width++ {
				carry := b
				c := mod_adc(a, width, &carry)
				C.Add(A, B)
				Carry.Rsh(C, uint(width))
				expectedCarry := Carry.Uint64()
				Mask.SetUint64(uint64(1)<<width - 1)
				C.And(C, Mask)
				expected := C.Uint64()
				if c != expected || expectedCarry != carry {
					t.Fatalf("adc(%d,%d,%d): Expecting %d carry %d but got %d carry %d", a, b, width, expected, expectedCarry, c, carry)
				}
			}
		}
	}
}
Esempio n. 21
0
func (f *Forge) Interact(player world.PlayerLike, action string) {
	switch action {
	default:
		f.VisibleObject.Interact(player, action)
	case "smelt":
		pos := f.Position()
		ppos := player.Position()
		if pos == nil || ppos == nil {
			return
		}
		x, y := pos.Position()
		if px, py := ppos.Position(); px != x || py != y+1 {
			player.SetSchedule(&world.ScheduleSchedule{
				Schedules: []world.Schedule{
					world.NewWalkSchedule(x, y, false, uint(player.Weight()/player.WeightMax())),
					&world.ActionSchedule{
						Target_: f,
						Action:  action,
					},
				},
			})
			return
		}
		ores := []interface{}{}
		for _, v := range player.Inventory() {
			if o, ok := v.(*Ore); ok {
				ores = append(ores, map[string]interface{}{
					"i": o.NetworkID(),
					"q": o.Material().Quality(),
					"v": o.Volume(),
					"w": o.Weight(),
				})
			}
		}
		for _, v := range player.Inventory() {
			if s, ok := v.(*Stone); ok {
				ores = append(ores, map[string]interface{}{
					"i": s.NetworkID(),
					"q": s.Material().Quality(),
					"v": s.Volume(),
					"w": s.Weight(),
				})
			}
		}
		instance := player.Instance(f.Position())
		var done time.Time
		instance.Last(func(last time.Time) time.Time {
			done = last
			return last
		})
		contents := []interface{}{}
		instance.Items(func(items []world.Visible) []world.Visible {
			for _, i := range items {
				var sprites []map[string]interface{}
				for j, c := range i.Colors() {
					sprites = append(sprites, map[string]interface{}{
						"S": i.Sprite(),
						"C": c,
						"E": map[string]interface{}{
							"y": j,
						},
					})
				}
				contents = append(contents, sprites)
				// 4 minutes per 5kg of ore
				done = done.Add(time.Minute * 4 * time.Duration(i.(world.Item).Weight()) / 5000)
			}
			if done.Before(time.Now()) && len(items) > 0 {
				materials := make(map[MetalType]*material)
				var quality big.Int
				var totalVolume uint64
				var tmp big.Int
				for _, i := range items {
					if o, ok := i.(*Ore); ok {
						for _, m := range o.material.components {
							if m.metal == nil || m.volume == 0 {
								continue
							}
							mat := materials[*m.metal]
							if mat == nil {
								mat = &material{metal: m.metal}
								materials[*m.metal] = mat
							}
							totalVolume += m.volume
							mat.volume += m.volume
							tmp.SetUint64(m.volume)
							quality.Add(&quality, tmp.Mul(&o.material.quality, &tmp))
						}
					}
				}
				originalVolume := totalVolume
				quality.Div(&quality, tmp.SetUint64(totalVolume))
				makeIngot := func(volume uint64) {
					ingot := &Ingot{}
					world.InitObject(ingot)
					ingot.material = &Material{
						components: make([]*material, 0, len((materials))),
						quality:    quality,
					}
					world.InitObject(ingot.material)
					remaining := originalVolume
					for _, m := range materials {
						v := m.volume * volume / remaining
						remaining -= m.volume
						volume -= v
						ingot.material.components = append(ingot.material.components, &material{
							metal:  m.metal,
							volume: v,
						})
					}
					ingot.material.sortComponents()
					if !player.GiveItem(ingot) {
						player.Position().Add(ingot)
					}
				}
				for totalVolume != 0 {
					if totalVolume <= 1000 {
						makeIngot(totalVolume)
						break
					}
					makeIngot(1000)
					totalVolume -= 1000
				}
				items = items[:0]
				contents = contents[:0]
			}
			return items
		})
		player.SetHUD("forge", map[string]interface{}{
			"O": ores,
			"C": contents,
			"T": done,
		})
	}
}
Esempio n. 22
0
func TestModShifts(t *testing.T) {
	A := new(big.Int)
	C := new(big.Int)
	for _, a := range numbers {
		A.SetUint64(a)
		for b := uint8(3); b < 96; b += 3 {
			var c uint64
			switch b {
			case 3:
				c = mod_shift3(a)
			case 6:
				c = mod_shift6(a)
			case 9:
				c = mod_shift9(a)
			case 12:
				c = mod_shift12(a)
			case 15:
				c = mod_shift15(a)
			case 18:
				c = mod_shift18(a)
			case 21:
				c = mod_shift21(a)
			case 24:
				c = mod_shift24(a)
			case 27:
				c = mod_shift27(a)
			case 30:
				c = mod_shift30(a)
			case 33:
				c = mod_shift33(a)
			case 36:
				c = mod_shift36(a)
			case 39:
				c = mod_shift39(a)
			case 42:
				c = mod_shift42(a)
			case 45:
				c = mod_shift45(a)
			case 48:
				c = mod_shift48(a)
			case 51:
				c = mod_shift51(a)
			case 54:
				c = mod_shift54(a)
			case 57:
				c = mod_shift57(a)
			case 60:
				c = mod_shift60(a)
			case 63:
				c = mod_shift63(a)
			case 66:
				c = mod_shift66(a)
			case 69:
				c = mod_shift69(a)
			case 72:
				c = mod_shift72(a)
			case 75:
				c = mod_shift75(a)
			case 78:
				c = mod_shift78(a)
			case 81:
				c = mod_shift81(a)
			case 84:
				c = mod_shift84(a)
			case 87:
				c = mod_shift87(a)
			case 90:
				c = mod_shift90(a)
			case 93:
				c = mod_shift93(a)
			}
			C.Lsh(A, uint(b))
			C.Mod(C, P)
			expected := C.Uint64()
			if c != expected {
				t.Fatalf("%d << %d: Expecting %d but got %d", a, b, expected, c)
			}
		}
	}
}
Esempio n. 23
0
// This program reads the quote key, generates a policy key,
// self-signs the policy cert, readsa the quote key info and
// signs a cert for the quote key with the new policy key.
func main() {
	policyKeyFile := flag.String("policyKeyFile", "policy_private.bin",
		"policy save file")
	policyKeyPassword := flag.String("policyKeyPassword", "xxzzy",
		"policy key password")
	policyCertFile := flag.String("policyCertFile", "policy_cert.der",
		"policy cert save file")
	quoteKeyInfoFile := flag.String("quoteKeyInfoFile", "quoteinfo.der",
		"quote info file name")
	quoteCertFile := flag.String("quoteCertFile", "quote_cert.der",
		"quote cert save file")

	flag.Parse()

	// Generate Policy key.
	policyKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		fmt.Printf("Can't generate policy key")
		return
	}
	fmt.Printf("policyKey: %x\n", policyKey)

	var notBefore time.Time
	notBefore = time.Now()
	validFor := 365 * 24 * time.Hour
	notAfter := notBefore.Add(validFor)

	// Self-sign policy key and save it.
	us := "US"
	issuerName := "PolicyAuthority"
	x509SubjectName := &pkix.Name{
		Organization:       []string{issuerName},
		OrganizationalUnit: []string{issuerName},
		CommonName:         issuerName,
		Country:            []string{us},
	}
	var sn big.Int
	sn.SetUint64(1)
	certificateTemplate := x509.Certificate{
		SerialNumber: &sn,
		Issuer:       *x509SubjectName,
		Subject:      *x509SubjectName,
		NotBefore:    notBefore,
		NotAfter:     notAfter,
		KeyUsage: x509.KeyUsageCertSign |
			x509.KeyUsageKeyAgreement | x509.KeyUsageDigitalSignature,
		BasicConstraintsValid: true,
		IsCA: true,
	}

	var priv interface{}
	var pub interface{}
	priv = policyKey
	pub = policyKey.Public()
	derPolicyCert, err := x509.CreateCertificate(rand.Reader, &certificateTemplate,
		&certificateTemplate, pub, priv)
	if err != nil {
		fmt.Printf("Can't self sign policy key\n")
		return
	}

	ioutil.WriteFile(*policyCertFile, derPolicyCert, 0644)
	if err != nil {
		fmt.Printf("Can't write policy cert\n")
		return
	}

	policyCert, err := x509.ParseCertificate(derPolicyCert)
	if err != nil {
		fmt.Printf("Can't parse policy cert\n")
		return
	}

	// Marshal policy key and save it.
	serializedPolicyKey, err := x509.MarshalECPrivateKey(policyKey)
	if err != nil {
		fmt.Printf("Cant serialize rsa key\n")
		return
	}

	ioutil.WriteFile(*policyKeyFile, serializedPolicyKey, 0644)
	if err == nil {
		fmt.Printf("Policy Key generation succeeded, password: %s\n",
			*policyKeyPassword)
	} else {
		fmt.Printf("Policy Key generation failed\n")
	}

	// Read request buffer
	buf, err := ioutil.ReadFile(*quoteKeyInfoFile)
	if err != nil {
		fmt.Printf("Can't read quote key info\n")
		return
	}
	var request tpm2.AttestCertRequest
	err = proto.Unmarshal(buf, &request)
	if err != nil {
		fmt.Printf("Can't unmarshal quote key info\n")
		return
	}

	// Should be an rsa key.
	if *request.KeyType != "rsa" {
		fmt.Printf("Quote key is not an rsa key\n")
		return
	}

	// Parse Der subject name.
	quoteKey, err := x509.ParsePKIXPublicKey(request.SubjectPublicKey)
	if err != nil {
		fmt.Printf("Can't parse quote key\n")
		return
	}

	// Sign quote certificate and save it.
	sn.SetUint64(2)
	localhost := "localhost"
	x509QuoteKeySubjectName := &pkix.Name{
		Organization:       []string{*request.KeyName},
		OrganizationalUnit: []string{*request.KeyName},
		CommonName:         localhost,
		Country:            []string{us},
	}
	quoteCertificateTemplate := x509.Certificate{
		SerialNumber: &sn,
		Issuer:       *x509SubjectName,
		Subject:      *x509QuoteKeySubjectName,
		NotBefore:    notBefore,
		NotAfter:     notAfter,
		KeyUsage: x509.KeyUsageCertSign |
			x509.KeyUsageKeyAgreement | x509.KeyUsageDigitalSignature,
	}
	derQuoteCert, err := x509.CreateCertificate(rand.Reader, &quoteCertificateTemplate,
		policyCert, quoteKey, priv)
	if err != nil {
		fmt.Printf("Can't self sign policy key\n")
		return
	}

	ioutil.WriteFile(*quoteCertFile, derQuoteCert, 0644)
	if err != nil {
		fmt.Printf("Can't write quote cert\n")
		return
	}
	fmt.Printf("Quote cert: %x\n", derQuoteCert)
}
Esempio n. 24
0
File: type.go Progetto: velour/stop
func newUint(x uint64) *big.Int {
	var i big.Int
	i.SetUint64(x)
	return &i
}
Esempio n. 25
0
// Prime returns a number, p, of the given size, such that p is prime
// with high probability.
// Prime will return error for any error returned by rand.Read or if bits < 2.
func Prime(rand io.Reader, bits int) (p *big.Int, err error) {
	if bits < 2 {
		err = errors.New("crypto/rand: prime size must be at least 2-bit")
		return
	}

	b := uint(bits % 8)
	if b == 0 {
		b = 8
	}

	bytes := make([]byte, (bits+7)/8)

	// Jeffrey hack
	p = big.NewInt(1<<uint(bits) - 1)
	for !p.ProbablyPrime(20) {
		p = p.Sub(p, big.NewInt(2))
	}
	return p, nil

	bigMod := new(big.Int)

	for {
		_, err = io.ReadFull(rand, bytes)
		if err != nil {
			return nil, err
		}

		// Clear bits in the first byte to make sure the candidate has a size <= bits.
		bytes[0] &= uint8(int(1<<b) - 1)
		// Don't let the value be too small, i.e, set the most significant two bits.
		// Setting the top two bits, rather than just the top bit,
		// means that when two of these values are multiplied together,
		// the result isn't ever one bit short.
		if b >= 2 {
			bytes[0] |= 3 << (b - 2)
		} else {
			// Here b==1, because b cannot be zero.
			bytes[0] |= 1
			if len(bytes) > 1 {
				bytes[1] |= 0x80
			}
		}
		// Make the value odd since an even number this large certainly isn't prime.
		bytes[len(bytes)-1] |= 1

		p.SetBytes(bytes)

		// Calculate the value mod the product of smallPrimes.  If it's
		// a multiple of any of these primes we add two until it isn't.
		// The probability of overflowing is minimal and can be ignored
		// because we still perform Miller-Rabin tests on the result.
		bigMod.Mod(p, smallPrimesProduct)
		mod := bigMod.Uint64()

	NextDelta:
		for delta := uint64(0); delta < 1<<20; delta += 2 {
			m := mod + delta
			for _, prime := range smallPrimes {
				if m%uint64(prime) == 0 && (bits > 6 || m != uint64(prime)) {
					continue NextDelta
				}
			}

			if delta > 0 {
				bigMod.SetUint64(delta)
				p.Add(p, bigMod)
			}
			break
		}

		// There is a tiny possibility that, by adding delta, we caused
		// the number to be one bit too long. Thus we check BitLen
		// here.
		if p.ProbablyPrime(20) && p.BitLen() == bits {
			return
		}
	}
}
func TestAttestProtocol(t *testing.T) {
	rw, err := OpenTPM("/dev/tpm0")
	if err != nil {
		t.Fatal("Can't open tpm")
	}
	defer rw.Close()

	policyKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal("Can't generate policy key")
	}

	notBefore := time.Now()
	validFor := 365 * 24 * time.Hour
	notAfter := notBefore.Add(validFor)

	us := "US"
	issuerName := "CloudProxyPolicy"
	x509SubjectName := &pkix.Name{
		Organization:       []string{issuerName},
		OrganizationalUnit: []string{issuerName},
		CommonName:         issuerName,
		Country:            []string{us},
	}
	var sn big.Int
	sn.SetUint64(1)
	certificateTemplate := x509.Certificate{
		SerialNumber: &sn,
		Issuer:       *x509SubjectName,
		Subject:      *x509SubjectName,
		NotBefore:    notBefore,
		NotAfter:     notAfter,
		KeyUsage: x509.KeyUsageCertSign |
			x509.KeyUsageKeyAgreement | x509.KeyUsageDigitalSignature,
		BasicConstraintsValid: true,
		IsCA: true,
	}

	var priv interface{}
	var pub interface{}
	priv = policyKey
	pub = policyKey.Public()
	derPolicyCert, err := x509.CreateCertificate(rand.Reader, &certificateTemplate,
		&certificateTemplate, pub, priv)
	if err != nil {
		t.Fatal("Can't self sign policy key ", err)
	}
	pcrs := []int{7}

	policyCert, err := x509.ParseCertificate(derPolicyCert)
	if err != nil {
		t.Fatal("Can't parse policy cert")
	}

	rootHandle, quoteHandle, storageHandle, err := CreateTpm2KeyHierarchy(rw, pcrs,
		2048, uint16(AlgTPM_ALG_SHA1), "01020304")
	if err != nil {
		t.Fatal("Can't create keys")
	}
	FlushContext(rw, storageHandle)
	FlushContext(rw, rootHandle)
	defer FlushContext(rw, quoteHandle)

	ekHandle, _, err := CreateEndorsement(rw, 2048, []int{7})
	if err != nil {
		t.Fatal("Can't create endorsement cert")
	}
	defer FlushContext(rw, ekHandle)

	ekPublicKey, err := GetRsaKeyFromHandle(rw, ekHandle)
	if err != nil {
		t.Fatal("Can't Create endorsement public key")
	}
	ekSubjectName := &pkix.Name{
		Organization:       []string{"Endorsement"},
		OrganizationalUnit: []string{"Endorsement"},
		CommonName:         "Endorsement",
		Country:            []string{us},
	}
	sn.SetUint64(2)
	ekTemplate := x509.Certificate{
		SerialNumber: &sn,
		Issuer:       *x509SubjectName,
		Subject:      *ekSubjectName,
		NotBefore:    notBefore,
		NotAfter:     notAfter,
		KeyUsage: x509.KeyUsageCertSign |
			x509.KeyUsageKeyAgreement | x509.KeyUsageDigitalSignature,
	}
	derEndorsementCert, err := x509.CreateCertificate(rand.Reader,
		&ekTemplate, policyCert, ekPublicKey, policyKey)
	if err != nil {
		t.Fatal("Can't sign endorsement key")
	}

	// Todo: make taoname
	taoName := "MachineCert"

	request, err := BuildAttestCertRequest(rw, quoteHandle, ekHandle, derEndorsementCert,
		taoName, "01020304")
	if err != nil {
		t.Fatal("Can't BuildAttestCertRequest")
	}

	response, err := ProcessQuoteDomainRequest(*request, policyKey, derPolicyCert)
	if err != nil {
		t.Fatal("Can't ProcessQuoteDomainRequest")
	}

	cert, err := GetCertFromAttestResponse(rw, quoteHandle, ekHandle, "01020304", *response)
	if err != nil {
		t.Fatal("Can't GetCertFromAttestResponse")
	}
	fmt.Printf("\nCert: %x\n", cert)
}
Esempio n. 27
0
// FromInt takes 64-bit integer and return KAPIID instance
func (c APIIDCtrl) FromInt(fpi uint64) KAPIID {
	i := new(big.Int)
	i.SetUint64(fpi)
	return KAPIID{slc: i.Bytes(), bigInt: i}
}
Esempio n. 28
0
// Prime returns a number, p, of the given size, such that p is prime
// with high probability.
// Prime will return error for any error returned by rand.Read or if bits < 2.
func PrimeWithPrefix(prefix []byte, bits int) (p *big.Int, err error) {
	if bits < 2 {
		err = errors.New("crypto/rand: prime size must be at least 2-bit")
		return
	}

	b := uint(bits % 8)
	if b == 0 {
		b = 8
	} else {
		return nil, errors.New("I don't know how to deal with non-multiples of 8")
	}
	c := 0

	bytes := make([]byte, (bits+7)/8)
	copy(bytes, prefix)
	p = new(big.Int)

	bigMod := new(big.Int)

	for {
		_, err = rand.Read(bytes[len(prefix):])
		if err != nil {
			return nil, err
		}

		// Make the value odd since an even number this large certainly isn't prime.
		bytes[len(bytes)-1] |= 1

		p.SetBytes(bytes)

		// Calculate the value mod the product of smallPrimes.  If it's
		// a multiple of any of these primes we add two until it isn't.
		// The probability of overflowing is minimal and can be ignored
		// because we still perform Miller-Rabin tests on the result.
		bigMod.Mod(p, smallPrimesProduct)
		mod := bigMod.Uint64()

	NextDelta:
		for delta := uint64(0); delta < 1<<20; delta += 2 {
			m := mod + delta
			for _, prime := range smallPrimes {
				if m%uint64(prime) == 0 && (bits > 6 || m != uint64(prime)) {
					continue NextDelta
				}
			}

			if delta > 0 {
				bigMod.SetUint64(delta)
				p.Add(p, bigMod)
			}
			break
		}

		// There is a tiny possibility that, by adding delta, we caused
		// the number to be one bit too long. Thus we check BitLen
		// here.
		if p.ProbablyPrime(20) && p.BitLen() == bits {
			return
		}
		c++
	}
}