private static String sha1Hash(Object[] input) {
    try {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      md.reset();

      for (Object o : input) {
        if (o instanceof String) {
          md.update(((String) o).getBytes("ISO_8859_1"));
        } else if (o instanceof byte[]) {
          md.update((byte[]) o);
        } else {
          return null;
        }
      }

      BigInteger bigInt = new BigInteger(md.digest());

      if (bigInt.compareTo(BigInteger.ZERO) < 0) {
        bigInt = bigInt.negate();
        return "-" + bigInt.toString(16);
      } else {
        return bigInt.toString(16);
      }
    } catch (Exception ioe) {
      return null;
    }
  }
Example #2
0
  private String doFileCheck() {
    File file = new File(fileField.getText().trim());
    StringBuilder sb = new StringBuilder("文件:\t");

    sb.append(fileField.getText().trim());
    sb.append('\n');

    BigInteger bint;

    if (md5check.isSelected()) {
      bint = getFileMD5(file);
      sb.append("MD5:\t");
      sb.append(bint.toString(16));
      sb.append('\n');
    }

    if (sha1check.isSelected()) {
      bint = getFileSHA1(file);
      sb.append("SHA-1:\t");
      sb.append(bint.toString(16));
      sb.append('\n');
    }

    if (crc32check.isSelected()) {
      bint = getFileCRC32(file);
      sb.append("CRC32:\t");
      sb.append(bint.toString(16));
      sb.append('\n');
    }

    sb.append("\n\n\n");
    return sb.toString();
  }
Example #3
0
  public static void shift(int order) {
    int failCount1 = 0;
    int failCount2 = 0;
    int failCount3 = 0;

    for (int i = 0; i < 100; i++) {
      BigInteger x = fetchNumber(order);
      int n = Math.abs(rnd.nextInt() % 200);

      if (!x.shiftLeft(n).equals(x.multiply(BigInteger.valueOf(2L).pow(n)))) failCount1++;

      BigInteger y[] = x.divideAndRemainder(BigInteger.valueOf(2L).pow(n));
      BigInteger z = (x.signum() < 0 && y[1].signum() != 0 ? y[0].subtract(BigInteger.ONE) : y[0]);

      BigInteger b = x.shiftRight(n);

      if (!b.equals(z)) {
        System.err.println("Input is " + x.toString(2));
        System.err.println("shift is " + n);

        System.err.println("Divided " + z.toString(2));
        System.err.println("Shifted is " + b.toString(2));
        if (b.toString().equals(z.toString())) System.err.println("Houston, we have a problem.");
        failCount2++;
      }

      if (!x.shiftLeft(n).shiftRight(n).equals(x)) failCount3++;
    }
    report("baz shiftLeft", failCount1);
    report("baz shiftRight", failCount2);
    report("baz shiftLeft/Right", failCount3);
  }
Example #4
0
  private String doTextCheck() {
    String text = textField.getText();
    StringBuilder sb = new StringBuilder("文本:\t");
    sb.append(textField.getText().trim());
    sb.append('\n');

    BigInteger bint;

    if (md5check.isSelected()) {
      bint = getTextMD5(text);
      sb.append("MD5:\t");
      sb.append(bint.toString(16));
      sb.append('\n');
    }

    if (sha1check.isSelected()) {
      bint = getTextSHA1(text);
      sb.append("SHA-1:\t");
      sb.append(bint.toString(16));
      sb.append('\n');
    }

    if (crc32check.isSelected()) {
      bint = getTextCRC32(text);
      sb.append("CRC32:\t");
      sb.append(bint.toString(16));
      sb.append('\n');
    }

    sb.append("\n\n\n");
    return sb.toString();
  }
Example #5
0
  /* (non-Javadoc)
   * @see org.eclipse.cdt.dsf.debug.service.IDisassembly#getInstructions(org.eclipse.cdt.dsf.debug.service.IDisassembly.IDisassemblyDMContext, java.math.BigInteger, java.math.BigInteger, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor)
   */
  public void getInstructions(
      IDisassemblyDMContext context,
      BigInteger startAddress,
      BigInteger endAddress,
      final DataRequestMonitor<IInstruction[]> drm) {
    // Validate the context
    if (context == null) {
      drm.setStatus(
          new Status(
              IStatus.ERROR,
              GdbPlugin.PLUGIN_ID,
              INTERNAL_ERROR,
              "Unknown context type",
              null)); //$NON-NLS-1$);
      drm.done();
      return;
    }

    // Go for it
    String start = (startAddress != null) ? startAddress.toString() : "$pc"; // $NON-NLS-1$
    String end = (endAddress != null) ? endAddress.toString() : "$pc + 100"; // $NON-NLS-1$
    fConnection.queueCommand(
        fCommandFactory.createMIDataDisassemble(context, start, end, false),
        new DataRequestMonitor<MIDataDisassembleInfo>(getExecutor(), drm) {
          @Override
          protected void handleSuccess() {
            IInstruction[] result = getData().getMIAssemblyCode();
            drm.setData(result);
            drm.done();
          }
        });
  }
Example #6
0
  public static void main(String[] args) {
    long time = System.currentTimeMillis();

    int c = 0;
    int i = 0;
    BigInteger two = new BigInteger("2");

    BigInteger n0, n1, n2;
    n0 = new BigInteger("0");
    n1 = new BigInteger("1");
    n2 = new BigInteger("1");

    BigInteger d0, d1, d2;
    d0 = new BigInteger("0");
    d1 = new BigInteger("1");
    d2 = new BigInteger("0");

    while (i++ <= 1000) {
      n0 = n1.multiply(two).add(n2);
      d0 = d1.multiply(two).add(d2);
      n2 = n1;
      d2 = d1;
      n1 = n0;
      d1 = d0;
      if (d0.toString().length() < n0.toString().length()) {
        c++;
      }
    }
    System.out.println("time: " + (System.currentTimeMillis() - time) + "ms");
    System.out.println(c);
  }
 public String saveSlot(String slotString, String username, String message) {
   BigInteger slot;
   try {
     slot = new BigInteger(slotString);
   } catch (Exception e) {
     return "lmao bye af thats not a real number";
   }
   JSONArray json = getJSON();
   int replaceIndex = -1;
   for (int i = 0; i < json.length(); i++) {
     JSONObject o = json.getJSONObject(i);
     if (o == null) continue;
     BigInteger current = new BigInteger(o.getString("slot"));
     if (current.equals(slot)) {
       if (!o.getString("name").equals(username)) {
         return "waohwo!!! " + o.getString("name") + " owns this savestate you dong !!";
       } else {
         replaceIndex = i;
         break;
       }
     }
   }
   JSONObject o = new JSONObject();
   o.put("name", username);
   o.put("slot", slot.toString());
   o.put("message", message);
   if (replaceIndex != -1) {
     json.remove(replaceIndex);
     json.put(replaceIndex, o);
   } else json.put(o);
   writeJSON(json);
   return "ur savestate was sav'd to slot " + slot.toString() + "! ^O^";
 }
Example #8
0
 /*public synchronized void generateKeys() {
     BigInteger p = new BigInteger(MillerRabin.ZnajdzPierwsza(bitlen/2));
     BigInteger q = new BigInteger(MillerRabin.ZnajdzPierwsza(bitlen/2));
     n = p.multiply(q);
     BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q
         .subtract(BigInteger.ONE));
     e = new BigInteger(2^(bits-2),rnd).shiftLeft(1).add(new BigInteger("1"));
     while (m.gcd(e).intValue() > 1) {
       e = e.add(new BigInteger("2"));
     }
     d = e.modInverse(m);
   }
 */
 public static void odczytPlikuTekstowegoE(String nazwa) throws IOException {
   RSA rsa = new RSA(1024);
   BigInteger n = rsa.n;
   BigInteger d = rsa.d;
   BigInteger e = rsa.e;
   BufferedWriter writer = new BufferedWriter(new FileWriter("zaszyfrowany.txt"));
   BufferedWriter writern = new BufferedWriter(new FileWriter("n.txt"));
   BufferedWriter writerd = new BufferedWriter(new FileWriter("d.txt"));
   writern.write(new String(n.toString()));
   writerd.write(new String(d.toString()));
   writern.close();
   writerd.close();
   FileInputStream fileInput = new FileInputStream(nazwa);
   int r;
   BigInteger bigIntText = new BigInteger("1");
   String text = "";
   while ((r = fileInput.read()) != -1) {
     // char c = (char) r;
     text += (char) r;
     bigIntText = new BigInteger(text.getBytes());
     if (bigIntText.compareTo(n) > 0) {
       text = text.substring(0, text.length() - 1);
       bigIntText = new BigInteger(text.getBytes());
       BigInteger wynik = bigIntText.modPow(e, n);
       writer.write(new String(wynik.toString()));
       writer.write(" ");
       text = "" + (char) r;
     }
   }
   BigInteger wynik = bigIntText.modPow(e, n);
   writer.write(new String(wynik.toString()));
   writer.close();
   fileInput.close();
 }
Example #9
0
  /** *************************************************************************** */
  public Fraction(String strFrac) // constructor
        /** *************************************************************************** */
      {
    int tokens = 0;
    String strTokens[] = new String[2];

    StringTokenizer tokenizer = new StringTokenizer(strFrac, "/");

    try {
      while (tokenizer.hasMoreTokens()) {
        strTokens[tokens] = tokenizer.nextToken();
        tokens++;
      }
    } catch (ArrayIndexOutOfBoundsException e) {
      throw new NumberFormatException(strFrac + " is not a valid fraction.");
    }

    if (tokens == 1) {
      strTokens[1] = new String("1");
    }

    num = new BigInteger(strTokens[0]);
    denom = new BigInteger(strTokens[1]);

    if (denom.equals(BigInteger.ZERO))
      throw new ArithmeticException(
          "Denominator in fraction cannot be zero: " + num.toString() + "/" + denom.toString());

    if (denom.signum() == -1) {
      num = num.negate();
      denom = denom.negate();
    }
  }
Example #10
0
 public void calculate_M2() {
   try {
     MessageDigest md = MessageDigest.getInstance("SHA-1");
     // Calculate H(N)
     M2 = new BigInteger(md.digest((A.toString() + M1.toString() + K.toString()).getBytes()));
   } catch (Exception e) {
   }
 }
Example #11
0
 /**
  * 获取序列号
  *
  * @see 实现类似于OracleSequence的效果
  */
 public static synchronized String buildSequenceNo() {
   if (sequenceNo.subtract(maxSequenceNo).signum() >= 0) {
     sequenceNo = new BigInteger("0");
     return sequenceNo.toString();
   }
   sequenceNo = sequenceNo.add(BigInteger.ONE);
   return sequenceNo.toString();
 }
Example #12
0
  public void calculate_u() {
    try {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      u = new BigInteger(md.digest((A.toString() + B.toString()).getBytes()));

    } catch (Exception e) {
    }
  }
Example #13
0
 void print() {
     if (denominator.compareTo(BigInteger.ONE) != 0) {
         System.out.printf("%s/%s", numerator.toString(), denominator.toString());
     } else {
         System.out.printf("%s", numerator.toString());
     }
     System.out.println();
 }
Example #14
0
 public void calculate_x() {
   try {
     MessageDigest md = MessageDigest.getInstance("SHA-1");
     x = new BigInteger(md.digest((s.toString() + p.toString()).getBytes()));
   } catch (Exception e) {
     System.out.println(e);
   }
 }
Example #15
0
 /** *************************************************************************** */
 public String toString()
       /** *************************************************************************** */
     {
   if (num.equals(BigInteger.ZERO)) return "0";
   else if (denom.equals(BigInteger.ONE)) return num.toString();
   else if (denom.equals(num)) return "1";
   else return new String(num.toString() + "/" + denom.toString());
 }
Example #16
0
 private static void _checkConvertibility(@Nonnull final BigInteger aSize) {
   if (aSize.compareTo(CGlobal.BIGINT_MAX_LONG) > 0)
     throw new IllegalArgumentException(
         "The passed BigInteger is too large to be converted into a long value: "
             + aSize.toString());
   if (aSize.compareTo(CGlobal.BIGINT_MIN_LONG) < 0)
     throw new IllegalArgumentException(
         "The passed BigInteger is too small to be converted into a long value: "
             + aSize.toString());
 }
Example #17
0
  public void calculate_M1() {
    BigInteger N_Hash;
    BigInteger g_Hash;
    BigInteger I_Hash;

    try {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      // Calculate H(N)
      N_Hash = new BigInteger(md.digest(N.toString().getBytes()));
      md.reset();

      // Calculate H(g)
      g_Hash = new BigInteger(md.digest(g.toString().getBytes()));
      md.reset();

      // Calculate H(I)
      I_Hash = new BigInteger(md.digest(I.toString().getBytes()));
      md.reset();

      // Calculate M1
      M1 =
          new BigInteger(
              md.digest(
                  (N_Hash.xor(g_Hash).toString()
                          + I_Hash.toString()
                          + s.toString()
                          + A.toString()
                          + B.toString()
                          + K.toString())
                      .getBytes()));
      System.out.println("Client M1: " + M1.toString());
    } catch (Exception e) {
    }
  }
Example #18
0
  public static void main(String[] args) {

    int n = 500; // number of 0's
    int m = 900; // number of 1's

    BigInteger calc = calc(n, m);
    System.out.println(calc.toString());

    BigInteger res = mod(calc(n, m));
    System.out.println(res.toString());
    // readInput();

  }
Example #19
0
 /** 将BigInteger以char形式读取,转换为String */
 private static String toString(BigInteger number) {
   String result = "";
   int lenth = number.toString().length();
   BigInteger temp = BigInteger.ZERO;
   BigInteger thousand = BigInteger.TEN.multiply(BigInteger.TEN).multiply(BigInteger.TEN);
   for (int i = 0; i < lenth; i += 3) {
     temp = number.mod(thousand);
     number = number.divide(thousand);
     result += (char) (Integer.parseInt(temp.toString()));
   }
   result = new StringBuffer(result).reverse().toString();
   return result;
 }
  @Override
  public String toString() {
    ensureReadParams();

    final StringBuilder sb = new StringBuilder("OpenSSLRSAPublicKey{");
    sb.append("modulus=");
    sb.append(modulus.toString(16));
    sb.append(',');
    sb.append("publicExponent=");
    sb.append(publicExponent.toString(16));
    sb.append('}');

    return sb.toString();
  }
Example #21
0
  public String toString() {
    if (!isMem) {
      return "NON-MEMOP (" + Integer.toString(stepNum) + ")";
    }

    final StringBuilder s = new StringBuilder();

    s.append(isLoad ? "LOAD" : "STORE");
    s.append(" ADDR=0x").append(addr.toString(16));
    s.append(" STEP=0x").append(Integer.toString(stepNum, 16));
    s.append(" DATA=0x").append(data.toString(16));

    return s.toString();
  }
  private void step1KeyDeploymentForU() throws Exception {
    ECCParameters secp160r1 = ECCTestHelper.getSecp160r1(injector);

    // Convert to octet string
    String dUOctetString = dU.toString(16);

    // Does it match our expectation?
    String expectedOctetString = "AA374FFC3CE144E6B073307972CB6D57B2A4E982";

    if (!ECCTestHelper.compare(dUOctetString, expectedOctetString)) {
      // No, throw an exception
      throw new Exception(
          "Failed at 2.1.2 1.2, expected " + expectedOctetString + ", got " + dUOctetString);
    }

    // Calculate Qu = (xU, yU) = dU * G
    Qu = secp160r1.getG().multiply(dU);

    // Validate Qu
    BigInteger xU = new BigInteger("466448783855397898016055842232266600516272889280", 10);
    BigInteger yU = new BigInteger("1110706324081757720403272427311003102474457754220", 10);

    // Does xU match?
    BigInteger QuX = Qu.getX().toBigInteger();

    if (!QuX.equals(xU)) {
      // No, throw an exception
      throw new Exception(
          "Failed at 2, Qu doesn't match xU.  Expected "
              + xU.toString(16)
              + ", got "
              + QuX.toString(16));
    }

    // Does yU match?
    BigInteger QuY = Qu.getY().toBigInteger();

    if (!QuY.equals(yU)) {
      // No, throw an exception
      throw new Exception(
          "Failed at 2, Qu doesn't match yU.  Expected "
              + yU.toString(16)
              + ", got "
              + QuY.toString(16));
    }

    // TODO - Validate the Qu octet string
    // String expectedQuOctetString = "0251b4496fecc406ed0e75a24a3c03206251419dc0";
  }
Example #23
0
 /** @param max the upper limit of the program */
 public static void run(BigInteger max) {
   // cycle through 1 to max
   for (BigInteger i = ONE; i.compareTo(max) == -1; i = i.add(ONE)) {
     // cycle through i to max
     for (BigInteger j = i; j.compareTo(max) == -1; j = j.add(ONE)) {
       if (relativelyPrime(i, j)) {
         if (optimalPair(i, j)) {
           // found an optimal pair!
           System.out.println(i.toString() + ", " + j.toString());
           totalPairs++;
         }
       }
     }
   }
 }
Example #24
0
  @Override
  public String toString() {
    ensureReadParams();

    final StringBuilder sb = new StringBuilder("OpenSSLDSAParams{");
    sb.append("G=");
    sb.append(g.toString(16));
    sb.append(",P=");
    sb.append(p.toString(16));
    sb.append(",Q=");
    sb.append(q.toString(16));
    sb.append('}');

    return sb.toString();
  }
Example #25
0
 // Converts our byte array into a hex string
 private String toHex(byte[] array) {
   BigInteger bigInt = new BigInteger(1, array);
   String hex = bigInt.toString(16);
   int paddingLength = (array.length * 2) - hex.length();
   if (paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex;
   else return hex;
 }
Example #26
0
  public static String getFileMD5(File file) {
    if (!file.isFile()) {
      return null;
    }
    MessageDigest digest = null;
    FileInputStream in = null;
    byte buffer[] = new byte[1024];
    int len;
    try {
      digest = MessageDigest.getInstance("MD5");
      in = new FileInputStream(file);
      while ((len = in.read(buffer, 0, 1024)) != -1) {
        digest.update(buffer, 0, len);
      }
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    BigInteger bigInt = new BigInteger(1, digest.digest());

    String md5Value = bigInt.toString(16);
    if (md5Value.length() < 32) {
      for (int i = 0; i < 32 - md5Value.length(); i++) {
        md5Value = "0" + md5Value;
      }
    }
    return md5Value.toLowerCase();
  }
Example #27
0
  private void send_client_DH_inner_data(long retry_id) {
    byte[] b_data = new byte[256];
    Common.random.nextBytes(b_data);

    BigInteger b = new BigInteger(1, b_data);
    BigInteger g_b = g.modPow(b, dh_prime);
    Common.logError(
        "g_b length: " + g_b.toByteArray().length + " -> " + Common.toBytes(g_b).length);

    BigInteger akey = g_a.modPow(b, dh_prime);
    Common.logError("auth_key: " + akey.toString());
    setAuthKey(Common.toBytes(akey));

    // gen data (client_DH_inner_data)
    TL.Object data_obj = TL.newObject("client_DH_inner_data", cl_nonce, sv_nonce, retry_id, g_b);
    byte[] data = data_obj.serialize();
    byte[] hash = Common.getSHA1(data);

    byte[] data_with_hash = new byte[(hash.length + data.length + 15) / 16 * 16];
    System.arraycopy(hash, 0, data_with_hash, 0, hash.length);
    System.arraycopy(data, 0, data_with_hash, hash.length, data.length);

    // send set_client_DH_params
    TL.Object req_obj =
        TL.newObject("set_client_DH_params", cl_nonce, sv_nonce, aes.IGE(data_with_hash, true));
    send(req_obj, false, false);
  }
Example #28
0
  public static String getMd5(File file) {
    if (file == null || !file.exists()) {
      return null;
    }

    String value = null;
    FileInputStream in = null;
    try {
      in = new FileInputStream(file);
      MappedByteBuffer byteBuffer =
          in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      md5.update(byteBuffer);
      BigInteger bi = new BigInteger(1, md5.digest());
      value = bi.toString(16);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (null != in) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return value;
  }
Example #29
0
 /**
  * Delete a titular. If the titular hadn't been added, the method return false.
  *
  * @see es.unileon.ulebank.handler.Handler}.
  * @param id ( The client id )
  * @return ( true if success, false otherwise )
  */
 public boolean deleteTitular(String dni) {
   boolean found = false;
   int i = 0;
   StringBuilder err = new StringBuilder();
   if (this.titulars.size() <= 1) {
     err.append("Error, the account must have at least one titular\n");
   } else {
     while (i < this.titulars.size() && !found) {
       if (this.titulars.get(i).getDni().compareTo(dni) == 0) {
         LOG.info("Delete " + dni.toString() + " titular");
         this.titulars.remove(i);
         found = true;
       }
       i++;
     }
     if (!found) {
       err.append("Cannot remove the titular ")
           .append(id.toString())
           .append(" because it doesn't exist");
     }
   }
   if (err.length() > 1) {
     found = false;
     LOG.error(err);
   }
   return found;
 }
 public void oldConvertPointerToInt(
     final ILocation loc, final ExpressionResult rexp, final CPrimitive newType) {
   assert newType.isIntegerType();
   assert rexp.lrVal.getCType() instanceof CPointer;
   if (OVERAPPROXIMATE_INT_POINTER_CONVERSION) {
     super.convertPointerToInt(loc, rexp, newType);
   } else {
     final Expression pointerExpression = rexp.lrVal.getValue();
     final Expression intExpression;
     if (mTypeSizes.useFixedTypeSizes()) {
       final BigInteger maxPtrValuePlusOne = mTypeSizes.getMaxValueOfPointer().add(BigInteger.ONE);
       final IntegerLiteral maxPointer = new IntegerLiteral(loc, maxPtrValuePlusOne.toString());
       intExpression =
           constructArithmeticExpression(
               loc,
               IASTBinaryExpression.op_plus,
               constructArithmeticExpression(
                   loc,
                   IASTBinaryExpression.op_multiply,
                   MemoryHandler.getPointerBaseAddress(pointerExpression, loc),
                   newType,
                   maxPointer,
                   newType),
               newType,
               MemoryHandler.getPointerOffset(pointerExpression, loc),
               newType);
     } else {
       intExpression = MemoryHandler.getPointerOffset(pointerExpression, loc);
     }
     final RValue rValue = new RValue(intExpression, newType, false, true);
     rexp.lrVal = rValue;
   }
 }