コード例 #1
0
def testObjectArgument():
    f = Foo()
    base = BigInteger.valueOf(12)
    result = base.multiply(BigInteger.valueOf(2))
    eq_(result.longValue(), f.doubleIt(base))
    eq_(result, Reflector.call(f, "doubleIt", [Number], [base]))
    eq_(len(Reflector.getExceptionTypes(f.getClass(), "doubleIt", [Number])), 2)
コード例 #2
0
def align(value):
    from java.math import BigInteger
    value_in_bytes = alignment_in_bytes(value)
    value_in_bytes = BigInteger(str(value_in_bytes))
    globals.template.template.setAlignment(
        BigInteger(str(value)), value_in_bytes,
        globals.template.get_caller_location())
コード例 #3
0
def testObjectArgument():
    f = Foo()
    base = BigInteger.valueOf(12)
    result = base.multiply(BigInteger.valueOf(2))
    eq_(result.longValue(), f.doubleIt(base))
    eq_(result, Reflector.call(f, "doubleIt", [Number], [base]))
    eq_(len(Reflector.getExceptionTypes(f.getClass(), "doubleIt", [Number])),
        2)
コード例 #4
0
ファイル: test_jbasic.py プロジェクト: ShinyArceus1/ROS-Code
 def test_java_objects(self):
     self.assertEquals(
         BigInteger('1234', 10).intValue(), 1234, 'BigInteger(string)')
     self.assertEquals(
         BigInteger([0x11, 0x11, 0x11]).intValue(), 0x111111,
         'BigInteger(byte[])')
     self.assertEquals(
         BigInteger(-1, [0x11, 0x11, 0x11]).intValue(), -0x111111,
         'BigInteger(int, byte[])')
コード例 #5
0
def testObjectArgument():
    f = Foo()
    base = BigInteger.valueOf(12)
    result = base.multiply(BigInteger.valueOf(2))
    eq_(result, f.doubleIt(base))
    eq_(result, Reflector.call(f, "doubleIt", [Number], [base]))
    #XXX: getting to the IFoo interface this way is brittle.
    iface = f.__class__.__base__.__bases__[0]
    excepts = Reflector.getExceptionTypes(iface, "doubleIt", [Number])
    eq_(len(excepts), 2)
コード例 #6
0
def testObjectArgument():
    f = Foo()
    base = BigInteger.valueOf(12)
    result = base.multiply(BigInteger.valueOf(2))
    eq_(result , f.doubleIt(base))
    eq_(result, Reflector.call(f, "doubleIt", [Number], [base]))
    #XXX: getting to the IFoo interface this way is brittle.
    iface = f.__class__.__base__.__bases__[0]
    excepts = Reflector.getExceptionTypes(iface, "doubleIt", [Number])
    eq_(len(excepts), 2)
コード例 #7
0
def sympyRat2jBigIntegerPair(val):
    numer = val.p # numerator
    if numer.bit_length() <= 63:
        numer = BigInteger.valueOf(numer)
    else:
        numer = BigInteger(str(numer))
    denom = val.q # denominator
    if denom.bit_length() <= 63:
        denom = BigInteger.valueOf(denom)
    else:
        denom = BigInteger(str(denom))
    return (numer, denom)
コード例 #8
0
def org(origin):
    from java.math import BigInteger
    if isinstance(origin, int):
        globals.template.template.setOrigin(
            BigInteger(str(origin)), globals.template.get_caller_location())
    elif isinstance(origin, dict):
        delta = origin.get('delta')
        if not isinstance(delta, int):
            raise TyperError('delta should be integer')
        globals.template.template.setRelativeOrigin(
            BigInteger(str(delta)), globals.template.get_caller_location())
    else:
        raise TypeError('origin should be integer or dict')
コード例 #9
0
    def section_data(self, attrs, contents=lambda: []):
        from java.math import BigInteger

        pa = attrs.get('pa')
        va = attrs.get('va')
        args = attrs.get('args')

        pa = BigInteger(str(pa))
        va = BigInteger(str(va))

        self.template.beginSectionData(pa, va, args)
        contents()
        self.template.endSection()
コード例 #10
0
 def check_big_compress_buffer(self, size, compress_func):
     _1M = 1024 * 1024
     if not is_jython:
         # Generate 10MB worth of random, and expand it by repeating it.
         # The assumption is that zlib's memory is not big enough to exploit
         # such spread out redundancy.
         fmt = "%%0%dx" % (2 * _1M)
         data = ''.join([binascii.a2b_hex(fmt % random.getrandbits(8 * _1M))
                         for i in range(10)])
         data = data * (size // len(data) + 1)
     else:
         #
         # The original version of this test passes fine on cpython,
         # but appears to hang on jython, because of the time taken to
         # format a very large integer as a hexadecimal string.
         # See this issue for details
         # http://bugs.jython.org/issue2013
         # Since testing string formatting is not the purpose of the test
         # it is necessary to generate the random test data in a different
         # way on jython. (There may be a better way than what I have 
         # implemented here)
         #
         from java.math import BigInteger
         from java.util import Random
         num_bits = 8 * _1M # causes "java.lang.OutOfMemoryError: Java heap space"
         num_bits = _1M
         data = ''.join([str(BigInteger((num_bits), Random()).toByteArray())
                         for i in range(10)])
     try:
         compress_func(data)
     finally:
         # Release memory
         data = None
コード例 #11
0
ファイル: io.py プロジェクト: mwinding/scripts
def parseNextIntLittleEndian(ra, count):
    # ra: a RandomAccessFile at the correct place to read the next sequence of bytes
    bytes = zeros(count + 1, 'b')
    ra.read(bytes, 0,
            count)  # ending zero will be the leading zero when reversed
    return BigInteger(
        reversed(bytes)).longValue()  # long to avoid bit overflows
コード例 #12
0
def set_tmode_reg_at(address, tmode):
    """attempt to set thumb mode register at address, true if register set"""
    # for thumb "register" value, will be None if not a thumb capable processor
    progCtx = getCurrentProgram().getProgramContext()
    tmodeReg = progCtx.getRegister("TMode")
    try:
        if tmode == 1:
            if tmodeReg:
                progCtx.setValue(tmodeReg, address, address, BigInteger("1"))
            else:
                warn("Thumb bit set without TMode register %s" % (address))
        else:
            progCtx.setValue(tmodeReg, address, address, BigInteger("0"))
        return True
    except ghidra.program.model.listing.ContextChangeException:
        warn("Set tmode failed at %s" % (address))
        return False
コード例 #13
0
def set_arguments_from_hash(builder, args):
    for name, value in args.iteritems():
        if isinstance(value, template.WrappedObject):
            value = value.java_object
        if isinstance(value, basestring):
            value = value
        if isinstance(value, int):
            builder.setArgument(name, BigInteger(str(value)))
        else:
            builder.setArgument(name, value)
コード例 #14
0
def readWKB(wkb):
    """
  Constructs a geometry from Well Known Binary.

  >>> 
  """
    if isinstance(wkb, (str, unicode)):
        from java.math import BigInteger
        wkb = BigInteger(wkb, 16).toByteArray()

    return _wkbreader.read(wkb)
コード例 #15
0
def rand(*args):
    from java.math import BigInteger
    if len(args) is 1:
        distribution = args[0]

        if not isinstance(distribution, Dist):
            raise TypeError('argument must be a distribution')

        return globals.template.template.newRandom(distribution.java_object)
    elif len(args) is 2:
        From = args[0]
        To = args[1]

        if not isinstance(From, int) or not isinstance(To, int):
            raise TypeError('arguments must be integers')

        return globals.template.template.newRandom(BigInteger(str(From)),
                                                   BigInteger(str(To)))
    else:
        raise TypeError('wrong argument count')
コード例 #16
0
 def org(self, origin):
     from java.math import BigInteger
     if type(origin) is int:
         self.builder.setOrigin(origin)
     elif type(origin) is dict:
         delta = origin.get('delta')
         if type(delta) is not int:
             raise TypeError("delta must be int")
         self.builder.setRelativeOrigin(BigInteger(str(delta)))
     else:
         raise TypeError("origin must be int or dict")
コード例 #17
0
def keyGenerating(primeBit, A):
    myPK = [0, 0, 0]
    batasBawah = pow(2, (primeBit - 1))
    up = primeBit
    batasAtas = (pow(2, up))
    batasAtas = batasAtas - 1
    prime = randint(batasBawah, batasAtas)
    prime = nonExshaustingPrimeGenerator.valueOf(prime)
    #prime = nonExshaustingPrimeGenerator.nextProbablePrime(prime)
    while (primality.pengujianMSR(prime) == False):
        prime = nonExshaustingPrimeGenerator.nextProbablePrime(
            prime)  #randint(batasBawah, batasAtas)
    prime = int(prime)
    alpha = primitiveRoot.GaussForPrimitiveRoot(prime)
    alpha_a = pow(alpha, A)
    alpha_a = alpha_a % prime
    myPK[0] = alpha
    myPK[1] = alpha_a
    myPK[2] = prime
    return myPK
コード例 #18
0
def variant(attrs={}, contents=lambda: []):
    name = attrs.get('name')
    bias = attrs.get('bias')
    from java.math import BigInteger
    if bias is not None:
        x = BigInteger(str(bias))
    else:
        x = bias
    globals.template.template.beginPreparatorVariant(name, x)
    contents()
    globals.template.template.endPreparatorVariant()
コード例 #19
0
    def define_space(self, attrs):
        from java.math import BigInteger
        id = attrs.get('id')
        text = attrs.get('text')
        fillWith = attrs.get('fill_with')

        self.configurer.defineSpace(id, text, BigInteger(str(fillWith)))

        def p(self, length):
            self.builder.addSpace(length)

        template_builder.define_method_for(DataManager, id, 'space', p)
コード例 #20
0
def create_preparator(is_comparator, attrs, contents=lambda: []):
    from java.math import BigInteger
    target = attrs.get('target')

    builder = globals.template.template.beginPreparator(target, is_comparator)
    builder.setWhere(globals.template.get_caller_location())

    name = attrs.get('name')

    if name is not None:
        builder.setName(name)

    mask = attrs.get('mask')
    if mask is not None:
        if isinstance(mask, basestring):
            builder.setMaskValue(mask)
        elif isintance(mask, list):
            builder.setMaskCollection(mask)
        else:
            raise TypeError("Illegal mask type")

    arguments = attrs.get('arguments')
    if arguments is not None:
        if not isinstance(arguments, dict):
            raise TypeError("arguments is not dict")

        for name, value in arguments.iteritems():
            if isinstance(value, int):
                builder.addArgumentValue(name, BigInteger(str(value)))
            elif isinstance(value, RangeClass):
                builder.addArgumentRange(name, BigInteger(str(value.min)),
                                         BigInteger(str(value.max)))
            elif isinstance(value, list):
                builder.addArgumentCollection(name, value)
            else:
                raise TypeError("Illegal value of argument")

    contents()
    globals.template.template.endPreparator()
コード例 #21
0
def set_arguments_from_array(builder, args):
    for value in args:
        if isinstance(args, list):
            set_arguments_from_array(builder, value)
        else:
            if isinstance(value, template.WrappedObject):
                value = value.java_object()
            if isinstance(value, basestring):
                value = value
            if isinstance(value, int):
                builder.addArgument(BigInteger(str(value)))
            else:
                if not isinstance(value, dict):
                    builder.addArgument(value)
コード例 #22
0
def convert_big_integer(value):
    """
    Convert the big integer value to long.
    :param value: big integer string or number value
    :return: converted to long
    """
    _method_name = 'convert_big_integer'
    converted_type = alias_constants.LONG
    converted = None
    if value is not None:
        try:
            converted = BigInteger(value).longValue()
        except NumberFormatException, nfe:
            _logger.fine('WLSDPLY-06774', value, type(value), nfe.getMessage(),
                         class_name=_class_name, method_name=_method_name)
コード例 #23
0
def get_pinsn_at(address, thumb=False):
    """
    attempt to dissemble adr, return PseudoInstruction or None
    for pre-analysis without affecting program

    """
    # NOTE in modules used from interpreter window, using the currentProgram
    # variable fails on tab switches (currentProgram is set at import time)
    cp = getCurrentProgram()
    mbi = MemoryBufferImpl(cp.getMemory(), address)
    # API changed in 9.2
    if ghidra.framework.ApplicationVersion(
            getGhidraVersion()) >= ghidra.framework.ApplicationVersion('9.2'):
        pci = ProcessorContextImpl(cp.getLanguage())
    else:
        pci = ProcessorContextImpl(cp.getProgramContext().getRegisters())

    treg = pci.getRegister('TMode')

    # don't try to set thumb reg if firmware not loaded as t
    if treg:
        if thumb:
            pci.setValue(pci.getRegister('TMode'), BigInteger("1"))
        else:
            pci.setValue(pci.getRegister('TMode'), BigInteger("0"))
    elif thumb:
        warn("ignoring Thumb set on non-t processor")

    try:
        ip = cp.getLanguage().parse(mbi, pci, False)
        pi = PseudoInstruction(address, ip, mbi, pci)
        return pi
    except (ghidra.program.model.lang.UnknownInstructionException,
            ghidra.program.model.lang.InsufficientBytesException,
            ghidra.program.model.address.AddressOverflowException):
        return None
コード例 #24
0
def print_format(kind, format, *args):
    import ru.ispras.microtesk.test.template.Value as Value
    from java.math import BigInteger

    builder = globals.template.template.newOutput(kind, format)

    for arg in args:
        if isinstance(arg, long) or isinstance(arg, basestring) or isinstance(
                arg, Value):
            builder.addArgument(arg)
        elif isinstance(arg, Location):
            builder.addArgument(arg.name, BigInteger(str(arg.index)))
        else:
            raise TypeError("Illegal format argument class")

    return globals.template.template.addOutput(builder.build())
コード例 #25
0
	def _myTurn(self):
		if self.lastReceivedBid != None and self.profile.getProfile().getUtility(self.lastReceivedBid).doubleValue() > 0.6:
			action = Accept(self.me, self.lastReceivedBid)
		else:
			bidspace = AllPartialBidsList(self.profile.getProfile().getDomain())
			bid = None
			for attempt in range(20):
				i = self.random.nextInt(bidspace.size()) # warning: jython implicitly converts BigInteger to long.
				bid = bidspace.get(BigInteger.valueOf(i))
				if self._isGood(bid):
					break
			action = Offer(self.me, bid);
		try:
			self.getConnection().send(action)
		except:
			print 'failed to send action '+action.toString()
			traceback.print_exc()
コード例 #26
0
 def parse(self, javaCert):
     '''
         Perform trasformation from java.security.X509Certificate to ssl_cert.X509Certificate
         @types: java.security.X509Certificate -> ssl_cert.X509Certificate
     '''
     typeCert = javaCert.getType()
     if typeCert == CertificateTypes.X509:
         objParser = DnParser()
         subject = javaCert.getSubjectDN().getName()
         issuedBy = javaCert.getIssuerDN().getName()
         subjectDn = objParser.parse(subject)
         issuedByDn = objParser.parse(issuedBy)
         version = javaCert.getVersion()
         create = javaCert.getNotBefore()
         expires = javaCert.getNotAfter()
         serialNumber = self.__bytesToHex(
             BigInteger(str(javaCert.getSerialNumber())).toByteArray())
         return X509Certificate(
             create, expires, LDAPDistinguishedObject(subjectDn, subject),
             LDAPDistinguishedObject(issuedByDn, issuedBy), serialNumber,
             javaCert.getSigAlgName(), typeCert, version)
     return None
コード例 #27
0
ファイル: PropNetAnnotater.py プロジェクト: hobson/ggpy
 def hashCode(self):
     """ generated source for method hashCode """
     bytes = self.name.__str__().getBytes()
     bigInt = BigInteger(bytes)
     val = bigInt.bitCount() + bigInt.intValue()
     return val + self.idx
コード例 #28
0
ファイル: cachelocation.py プロジェクト: HienTH/autopsy
    def __findGeoLocationsInFile(self, file, abstractFile):

        tempBytes = bytearray([0] * 2) # will temporarily hold bytes to be converted into the correct data types

        try:
            inputStream = FileInputStream(file)

            inputStream.read(tempBytes) # version

            tempBytes = bytearray([0] * 2)
            inputStream.read(tempBytes) # number of location entries

            iterations = BigInteger(tempBytes).intValue()

            for i in range(iterations): # loop through every entry
                tempBytes = bytearray([0] * 2)
                inputStream.read(tempBytes)

                tempBytes = bytearray([0])
                inputStream.read(tempBytes)

                while BigInteger(tempBytes).intValue() != 0: # pass through non important values until the start of accuracy(around 7-10 bytes)
                    if 0 > inputStream.read(tempBytes):
                        break # we've passed the end of the file, so stop

                tempBytes = bytearray([0] * 3)
                inputStream.read(tempBytes)
                if BigInteger(tempBytes).intValue() <= 0: # This refers to a location that could not be calculated
                    tempBytes = bytearray([0] * 28) # read rest of the row's bytes
                    inputStream.read(tempBytes)
                    continue
                accuracy = "" + BigInteger(tempBytes).intValue()

                tempBytes = bytearray([0] * 4)
                inputStream.read(tempBytes)
                confidence = "" + BigInteger(tempBytes).intValue()

                tempBytes = bytearray([0] * 8)
                inputStream.read(tempBytes)
                latitude = CacheLocationAnalyzer.toDouble(bytes)

                tempBytes = bytearray([0] * 8)
                inputStream.read(tempBytes)
                longitude = CacheLocationAnalyzer.toDouble(bytes)

                tempBytes = bytearray([0] * 8)
                inputStream.read(tempBytes)
                timestamp = BigInteger(tempBytes).longValue() / 1000

                attributes = ArrayList()
                artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_TRACKPOINT)
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE, AndroidAnalyzer.MODULE_NAME, latitude))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE, AndroidAnalyzer.MODULE_NAME, longitude))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, AndroidModuleFactorymodule.Name, timestamp))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PROG_NAME, AndroidAnalyzer.MODULE_NAME,
                    file.getName() + "Location History"))

                artifact.addAttributes(attributes)
                #Not storing these for now.
                #    artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(), AndroidModuleFactorymodule.moduleName, accuracy))
                #    artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_COMMENT.getTypeID(), AndroidModuleFactorymodule.moduleName, confidence))
                try:
                    # index the artifact for keyword search
                    blackboard = Case.getCurrentCase().getServices().getBlackboard()
                    blackboard.indexArtifact(artifact)
                except Blackboard.BlackboardException as ex:
                    self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + artifact.getArtifactID(), ex)
                    self._logger.log(Level.SEVERE, traceback.format_exc())
                    MessageNotifyUtil.Notify.error("Failed to index GPS trackpoint artifact for keyword search.", artifact.getDisplayName())

        except Exception as ex:
            self._logger.log(Level.SEVERE, "Error parsing Cached GPS locations to blackboard", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
コード例 #29
0
def parseNextIntLittleEndian(ra, count):
    # ra.read() reads a single byte as an unsigned int
    return BigInteger(reversed([ra.readByte()
                                for _ in xrange(count)])).intValue()
コード例 #30
0
 def entry_point(org, exception, contents=lambda: []):
     from java.math import BigInteger
     builder.beginEntryPoint(BigInteger(str(org)), exception)
     contents()
     return builder.endEntryPoint()
コード例 #31
0
 def _longRandomPrime():
     BigInteger prime = BigInteger.probablePrime(31, new Random())
     return prime.longValue()
コード例 #32
0
ファイル: test.py プロジェクト: andreisavu/playrsa
if __name__ == '__main__':
    bits = 32

    P = get_probable_prime(bits/2)
    Q = get_probable_prime(bits/2)
    print 'P: %s, Q: %s' % (P, Q)

    N = P.multiply(Q)
    print 'N: %s' % N

    one = BigInteger("1")
    Euler = P.subtract(one).multiply(Q.subtract(one))
    print 'Euler: %s' % Euler

    E = BigInteger("17")
    print 'E: %s' % E

    try:
        D = E.modInverse(Euler)
        print 'D: %s' % D
    except ArithmeticException:
        print >>sys.stderr, 'Failed. E is not invertible'
        sys.exit(1)

    msg = 'A test message'
    print 'Original message: %s' % msg

    result = []
    for ch in msg:
        result.append(BigInteger.valueOf(ord(ch)).modPow(E, N))
コード例 #33
0
def toInt(a):
    return BigInteger("%i" % a).intValue()
コード例 #34
0
ファイル: test.py プロジェクト: andreisavu/playrsa
def get_probable_prime(bits):
    return BigInteger.probablePrime(bits/2, randomizer)
コード例 #35
0
ファイル: crclclient.py プロジェクト: usnistgov/crcl
from crcl.base import *
from crcl.utils import CRCLSocket
from crcl.utils import CRCLPosemath
from java.math import BigInteger
from java.math import BigDecimal
import java.lang.Boolean

print "Connect"
s = CRCLSocket("localhost", 64444)
#s.setEXIEnabled(True)
instance = CRCLCommandInstanceType()

## Create and send InitCanon command
print "Send InitCanon"
init = InitCanonType()
init.setCommandID(BigInteger.valueOf(7))
instance.setCRCLCommand(init)
s.writeCommand(instance)
#    
## Create and send MoveTo command.
print "Send MoveTo"
moveTo = MoveToType()
moveTo.setCommandID(BigInteger.valueOf(8))
pt = CRCLPosemath.point(0.6,0.1,0.1)
xaxis = CRCLPosemath.vector(1.0,0.0,0.0)
zaxis = CRCLPosemath.vector(0.0,0.0,1.0)
pose = CRCLPosemath.pose(pt,xaxis,zaxis)
moveTo.setEndPosition(pose)
moveTo.setMoveStraight(java.lang.Boolean.FALSE)
instance.setCRCLCommand(moveTo)
s.writeCommand(instance)
コード例 #36
0
expected = 0
for i in vec:
    assert i == expected, 'testing __iter__ on java.util.Vector'
    expected = expected + 1

expected = 0
for i in iter(vec):
    assert i == expected, 'testing iter(java.util.Vector)'
    expected = expected + 1

print_test('create java objects', 2)

from java.math import BigInteger

assert BigInteger('1234', 10).intValue() == 1234, 'BigInteger(string)'
assert BigInteger([0x11, 0x11,
                   0x11]).intValue() == 0x111111, 'BigInteger(byte[])'
assert BigInteger(
    -1, [0x11, 0x11, 0x11]).intValue() == -0x111111, 'BigInteger(int, byte[])'

print_test('call static methods')
s1 = String.valueOf(['1', '2', '3'])
s2 = String.valueOf('123')
s3 = String.valueOf(123)
s4 = String.valueOf(123l)
s5 = String.valueOf(['0', '1', '2', '3', 'a', 'b'], 1, 3)
assert s1 == s2 == s3 == s4 == s5, 'String.valueOf method with different arguments'

print_test('call instance methods')
s = String('hello')
コード例 #37
0
 def align(self, value):
     from java.math import BigInteger
     value_in_bytes = alignment_in_bytes(value)
     return self.builder.align(BigInteger(str(value)),
                               BigInteger(str(value_in_bytes)))