Example #1
0
func TestDecryptOAEP(t *testing.T) {
	random := rand.Reader

	sha1 := sha1.New()
	n := new(big.Int)
	d := new(big.Int)
	for i, test := range testEncryptOAEPData {
		n.SetString(test.modulus, 16)
		d.SetString(test.d, 16)
		private := new(PrivateKey)
		private.PublicKey = PublicKey{n, test.e}
		private.D = d

		for j, message := range test.msgs {
			out, err := DecryptOAEP(sha1, nil, private, message.out, nil)
			if err != nil {
				t.Errorf("#%d,%d error: %s", i, j, err)
			} else if bytes.Compare(out, message.in) != 0 {
				t.Errorf("#%d,%d bad result: %#v (want %#v)", i, j, out, message.in)
			}

			// Decrypt with blinding.
			out, err = DecryptOAEP(sha1, random, private, message.out, nil)
			if err != nil {
				t.Errorf("#%d,%d (blind) error: %s", i, j, err)
			} else if bytes.Compare(out, message.in) != 0 {
				t.Errorf("#%d,%d (blind) bad result: %#v (want %#v)", i, j, out, message.in)
			}
		}
		if testing.Short() {
			break
		}
	}
}
Example #2
0
// TODO: handle flonums, compnums, ratnums, etc
func _string_to_number(_str Obj, _radix Obj) Obj {
	if is_immediate(_str) {
		panic("bad type")
	}
	str := string((*_str).([]int))

	radix := number_to_int(_radix)
	switch {
	case strings.HasPrefix(str, "#b"):
		radix = 2
		str = str[2:]
	case strings.HasPrefix(str, "#o"):
		radix = 8
		str = str[2:]
	case strings.HasPrefix(str, "#d"):
		radix = 10
		str = str[2:]
	case strings.HasPrefix(str, "#x"):
		radix = 16
		str = str[2:]
	}

	var v big.Int
	z, s := v.SetString(str, radix)
	if !s {
		return False
	}
	if z.Cmp(fixnum_max_Int) < 1 && z.Cmp(fixnum_min_Int) > -1 {
		return Make_fixnum(int(z.Int64()))
	}
	return wrap(z)
}
Example #3
0
func TestDecryptOAEP(t *testing.T) {
	urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0)
	if err != nil {
		t.Errorf("Failed to open /dev/urandom")
	}

	sha1 := sha1.New()
	n := new(big.Int)
	d := new(big.Int)
	for i, test := range testEncryptOAEPData {
		n.SetString(test.modulus, 16)
		d.SetString(test.d, 16)
		private := PrivateKey{PublicKey{n, test.e}, d, nil, nil}

		for j, message := range test.msgs {
			out, err := DecryptOAEP(sha1, nil, &private, message.out, nil)
			if err != nil {
				t.Errorf("#%d,%d error: %s", i, j, err)
			} else if bytes.Compare(out, message.in) != 0 {
				t.Errorf("#%d,%d bad result: %#v (want %#v)", i, j, out, message.in)
			}

			// Decrypt with blinding.
			out, err = DecryptOAEP(sha1, urandom, &private, message.out, nil)
			if err != nil {
				t.Errorf("#%d,%d (blind) error: %s", i, j, err)
			} else if bytes.Compare(out, message.in) != 0 {
				t.Errorf("#%d,%d (blind) bad result: %#v (want %#v)", i, j, out, message.in)
			}
		}
	}
}
Example #4
0
/**
 * Store partial product result lines in the Calculator output lines.
 */
func (calc *Calculator) setPartialLines() {
	var (
		opDigits = calc.operands[1].String()
		opLength = len(opDigits)
	)

	// From largest to smallest place values (i.e., last to first partial result
	// lines)
	for index, digit := range opDigits {
		var (
			placeValue big.Int
			buffer     bytes.Buffer

			// Amount of right indentation this line has and also the position
			// relative to the first partial result line (right after the first
			// ruler)
			offset = opLength - index - 1
		)

		placeValue.SetString(fmt.Sprintf("%c", digit), 10)
		placeValue.Mul(&placeValue, &calc.operands[0])

		// We're right-padding with spaces, but these will be stripped out later
		buffer.WriteString(placeValue.String())
		buffer.WriteString(strings.Repeat(" ", offset))

		calc.lines[3+offset] = buffer.String()
	}
}
Example #5
0
// MakeConst makes an ideal constant from a literal
// token and the corresponding literal string.
func MakeConst(tok token.Token, lit string) Const {
	switch tok {
	case token.INT:
		var x big.Int
		_, ok := x.SetString(lit, 0)
		assert(ok)
		return Const{&x}
	case token.FLOAT:
		var y big.Rat
		_, ok := y.SetString(lit)
		assert(ok)
		return Const{&y}
	case token.IMAG:
		assert(lit[len(lit)-1] == 'i')
		var im big.Rat
		_, ok := im.SetString(lit[0 : len(lit)-1])
		assert(ok)
		return Const{cmplx{big.NewRat(0, 1), &im}}
	case token.CHAR:
		assert(lit[0] == '\'' && lit[len(lit)-1] == '\'')
		code, _, _, err := strconv.UnquoteChar(lit[1:len(lit)-1], '\'')
		assert(err == nil)
		return Const{big.NewInt(int64(code))}
	case token.STRING:
		s, err := strconv.Unquote(lit)
		assert(err == nil)
		return Const{s}
	}
	panic("unreachable")
}
Example #6
0
func NewInteger(arg Any) *Integer {
	var result big.Int
	switch arg.(type) {
	case int:
		result.SetInt64(int64(arg.(int)))
	case int64:
		result.SetInt64(arg.(int64))
	case uint64:
		result.SetString(strconv.Uitoa64(arg.(uint64)), 0)
	case string:
		result.SetString(arg.(string), 0)
	default:
		panic(fmt.Sprintf("Can not convert %T to Integer", arg))
	}
	return (*Integer)(&result)
}
Example #7
0
// NewCalculator constructs a new Calculator by reading test case data from
// input.
func NewCalculator(reader *bufio.Reader) *Calculator {
	var total, diff big.Int

	if line, err := reader.ReadString('\n'); err != nil {
		panic(err)
	} else {
		total.SetString(line, 10)
	}

	if line, err := reader.ReadString('\n'); err != nil {
		panic(err)
	} else {
		diff.SetString(line, 10)
	}

	return &Calculator{total: &total, diff: &diff}
}
Example #8
0
func TestEncryptOAEP(t *testing.T) {
	sha1 := sha1.New()
	n := new(big.Int)
	for i, test := range testEncryptOAEPData {
		n.SetString(test.modulus, 16)
		public := PublicKey{n, test.e}

		for j, message := range test.msgs {
			randomSource := bytes.NewBuffer(message.seed)
			out, err := EncryptOAEP(sha1, randomSource, &public, message.in, nil)
			if err != nil {
				t.Errorf("#%d,%d error: %s", i, j, err)
			}
			if bytes.Compare(out, message.out) != 0 {
				t.Errorf("#%d,%d bad result: %x (want %x)", i, j, out, message.out)
			}
		}
	}
}
Example #9
0
func bigFromString(s string) *big.Int {
	ret := new(big.Int)
	ret.SetString(s, 10)
	return ret
}
Example #10
0
func fromBase10(base10 string) *big.Int {
	i := new(big.Int)
	i.SetString(base10, 10)
	return i
}
Example #11
0
/**
 * Find the next palindrome after the current number.
 */
func (factory *PalinFactory) Next() string {
	var (
		buffer bytes.Buffer

		numberLen = len(factory.number)
		oddLength = numberLen%2 > 0

		// Greedily split the number into two halves.  Greedily meaning for
		// odd-length numbers, the middle digit belongs to both sides (e.g.,
		// "987" splits into "98" and "87").
		leftSide     = factory.number[0 : (numberLen+1)/2]
		rightSide    = factory.number[numberLen/2:]
		mirroredSide = Reverse(leftSide)

		leftLength = len(leftSide)
	)

	// Before we create a palindrome, we can determine if the resulting
	// palindrome will not be greater than the original number by mirroring the
	// left side and comparing it to the right side.
	//
	// Using 123456 as an example, the palindrome will be 123321, which is less
	// than 123456.  If we mirror the left side, we get 321.  The right side is
	// 456.  Since 321 <= 456, we know the palindrome will not be greater than
	// the original number.
	if !Greater(mirroredSide, rightSide) {
		// Since it is not greater, we can increment the palindrome by
		// incrementing the left side.  This is essentially incrementing the
		// middle digits of the palindrome, which results in the very next
		// palindrome.  Since we are also incrementing the left side, the
		// resulting palindrome will also be greater than the original number.
		leftSide = Increment(leftSide)

		// One obvious optimization is to set leftSide here and then set it
		// again in the next inner if {}, rather than calling leftValue.String()
		// twice, but that seems to consistently be slower for some reason.

		// If we introduced a new digit, this changes the evenness/oddness of
		// the number, and we need to account for this when constructing the
		// palindrome.  Since we greedily split the number, going from odd to
		// even means we need to drop a digit on the left.
		//
		// For example, the left side of 999 is "99".  The left side of 1001 is
		// "10".  Notice both have two digits.  However, if we increment "99"
		// (as a left side), we get "100", so we need to divide by 10 to get the
		// two digits that will be mirrored to form the palindrome 1001.  This
		// doesn't need to be done when going from odd to even, because the left
		// side has one more digit (left side of 99 is "9", left side of 101 is
		// "10").
		if len(leftSide) != leftLength {
			oddLength = !oddLength

			if !oddLength {
				var leftValue big.Int

				leftValue.SetString(leftSide, 10)
				leftValue.Div(&leftValue, big.NewInt(10))
				leftSide = leftValue.String()
			}
		}

		mirroredSide = Reverse(leftSide)
	}

	buffer.WriteString(leftSide)

	// Mirror the left side onto the right to form a palindrome
	if oddLength {
		// When odd, the left and right sides "overlap" on the middle digit, so
		// don't include in on the right
		buffer.WriteString(mirroredSide[1:])
	} else {
		buffer.WriteString(mirroredSide)
	}

	return buffer.String()
}
func main() {
	// integer
	is := "1234"
	fmt.Println("original:   ", is)
	i, err := strconv.Atoi(is)
	if err != nil {
		fmt.Println(err)
		return
	}
	// assignment back to original variable shows result is the same type.
	is = strconv.Itoa(i + 1)
	fmt.Println("incremented:", is)

	// error checking worthwhile
	fmt.Println()
	_, err = strconv.Atoi(" 1234") // whitespace not allowed
	fmt.Println(err)
	_, err = strconv.Atoi("12345678901")
	fmt.Println(err)
	_, err = strconv.Atoi("_1234")
	fmt.Println(err)
	_, err = strconv.Atof64("12.D34")
	fmt.Println(err)

	// float
	fmt.Println()
	fs := "12.34"
	fmt.Println("original:   ", fs)
	f, err := strconv.Atof64(fs)
	if err != nil {
		fmt.Println(err)
		return
	}
	// various options on Ftoa64 produce different formats.  All are valid
	// input to Atof64, so result format does not have to match original
	// format.  (Matching original format would take a lot of code.)
	fs = strconv.Ftoa64(f+1, 'g', -1)
	fmt.Println("incremented:", fs)
	fs = strconv.Ftoa64(f+1, 'e', 4)
	fmt.Println("what format?", fs)

	// complex
	// strconv package doesn't handle complex types, but fmt does.
	// (fmt can be used on ints and floats too, but strconv is more efficient.)
	fmt.Println()
	cs := "(12+34i)"
	fmt.Println("original:   ", cs)
	var c complex128
	_, err = fmt.Sscan(cs, &c)
	if err != nil {
		fmt.Println(err)
		return
	}
	cs = fmt.Sprint(c + 1)
	fmt.Println("incremented:", cs)

	// big integers have their own functions
	fmt.Println()
	bs := "170141183460469231731687303715884105728"
	fmt.Println("original:   ", bs)
	var b, one big.Int
	_, ok := b.SetString(bs, 10)
	if !ok {
		fmt.Println("big.SetString fail")
		return
	}
	one.SetInt64(1)
	bs = b.Add(&b, &one).String()
	fmt.Println("incremented:", bs)
}