Example #1
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 #2
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 #3
0
  /**
   * Validates the zero knowledge proof (generated by {@link
   * #calculateZeroKnowledgeProof(BigInteger, BigInteger, BigInteger, BigInteger, BigInteger,
   * String, Digest, SecureRandom)}) is correct.
   *
   * @throws CryptoException if the zero knowledge proof is not correct
   */
  public static void validateZeroKnowledgeProof(
      BigInteger p,
      BigInteger q,
      BigInteger g,
      BigInteger gx,
      BigInteger[] zeroKnowledgeProof,
      String participantId,
      Digest digest)
      throws CryptoException {

    /* sig={g^v,r} */
    BigInteger gv = zeroKnowledgeProof[0];
    BigInteger r = zeroKnowledgeProof[1];

    BigInteger h = calculateHashForZeroKnowledgeProof(g, gv, gx, participantId, digest);
    if (!(gx.compareTo(ZERO) == 1
        && // g^x > 0
        gx.compareTo(p) == -1
        && // g^x < p
        gx.modPow(q, p).compareTo(ONE) == 0
        && // g^x^q mod q = 1
        /*
         * Below, I took an straightforward way to compute g^r * g^x^h,
         * which needs 2 exp. Using a simultaneous computation technique
         * would only need 1 exp.
         */
        g.modPow(r, p).multiply(gx.modPow(h, p)).mod(p).compareTo(gv) == 0)) // g^v=g^r * g^x^h
    {
      throw new CryptoException("Zero-knowledge proof validation failed");
    }
  }
Example #4
0
  // Determines if a specified integer is prime using the Miller-Rabin
  // primality test.
  //
  // Performance: O(k log^3(n))
  //
  // Args:
  //    n (BigInteger): The number to perform the primality test.
  //           k (int): The number of iterations to perform.
  //
  // Returns:
  //    (bool): Denotes the results of the primality test.
  public boolean is_prime(BigInteger n, int k) {
    if (n.compareTo(TWO) < 0) return false;
    else if (n.compareTo(TWO) == 0) return true;
    else if (n.mod(TWO).compareTo(ZERO) == 0) return false;

    BigInteger i = ZERO;

    // Express n - 1 = 2^i * d, where d is odd by
    // factoring powers of 2 from n - 1.
    while (true) {
      BigInteger modulus = TWO.pow(i.intValue());
      BigInteger m = n.subtract(ONE).mod(modulus);

      if (m.compareTo(ZERO) == 0) i = i.add(ONE);
      else if (m.compareTo(ZERO) > 0) break;
    }

    i = i.subtract(ONE);

    BigInteger divisor = TWO.pow(i.intValue());
    BigInteger d = n.subtract(ONE).divide(divisor);

    // The more k iterations, the more accurate the result. It decreases
    // the likelihood of a composite number passing the Miller-Rabin test.
    for (int j = 0; j < k; ++j) {
      // Pick a random integer a in the range [2, n - 1].
      BigInteger a = random(TWO, n.subtract(ONE));

      // Let x = a^d mod n.
      BigInteger x = a.modPow(d, n);

      // Either n is prime or a is a strong liar for n. Try another
      // random a to determine if a is truly prime.
      if (x.compareTo(ONE) == 0 || x.compareTo(n.subtract(ONE)) == 0) continue;

      boolean flag = false;

      // Repeat i - 1 times to determine if n is prime.
      for (BigInteger p = ZERO; p.compareTo(i.subtract(ONE)) < 0; p = p.add(ONE)) {
        // Let x = x^2 mod n.
        x = x.modPow(TWO, n);

        // Retry with another random a.
        if (x.compareTo(n.subtract(ONE)) == 0) {
          flag = true;
          break;
        }
      }

      // Most likely n is composite.
      if (!flag) return false;
    }

    return true;
  }
  public static boolean verifySignature(byte[] message, DSASignature ds, DSAPublicKey dpk)
      throws IOException {
    /* Inspired by Bouncycastle's DSASigner class */

    SHA1 md = new SHA1();
    md.update(message);
    byte[] sha_message = new byte[md.getDigestLength()];
    md.digest(sha_message);

    BigInteger m = new BigInteger(1, sha_message);

    BigInteger r = ds.getR();
    BigInteger s = ds.getS();

    BigInteger g = dpk.getG();
    BigInteger p = dpk.getP();
    BigInteger q = dpk.getQ();
    BigInteger y = dpk.getY();

    BigInteger zero = BigInteger.ZERO;

    if (log.isEnabled()) {
      log.log(60, "ssh-dss signature: m: " + m.toString(16));
      log.log(60, "ssh-dss signature: r: " + r.toString(16));
      log.log(60, "ssh-dss signature: s: " + s.toString(16));
      log.log(60, "ssh-dss signature: g: " + g.toString(16));
      log.log(60, "ssh-dss signature: p: " + p.toString(16));
      log.log(60, "ssh-dss signature: q: " + q.toString(16));
      log.log(60, "ssh-dss signature: y: " + y.toString(16));
    }

    if (zero.compareTo(r) >= 0 || q.compareTo(r) <= 0) {
      log.log(20, "ssh-dss signature: zero.compareTo(r) >= 0 || q.compareTo(r) <= 0");
      return false;
    }

    if (zero.compareTo(s) >= 0 || q.compareTo(s) <= 0) {
      log.log(20, "ssh-dss signature: zero.compareTo(s) >= 0 || q.compareTo(s) <= 0");
      return false;
    }

    BigInteger w = s.modInverse(q);

    BigInteger u1 = m.multiply(w).mod(q);
    BigInteger u2 = r.multiply(w).mod(q);

    u1 = g.modPow(u1, p);
    u2 = y.modPow(u2, p);

    BigInteger v = u1.multiply(u2).mod(p).mod(q);

    return v.equals(r);
  }
  /**
   * Call to save the public key (value B in the docs) when received from the server
   *
   * @param publicKey_B B
   * @throws SRPAuthenticationFailedException if B is invalid
   */
  public void setServerPublicKey_B(BigInteger publicKey_B) throws SRPAuthenticationFailedException {
    if (fPublicKey_A == null) {
      throw new IllegalStateException("setSalt_s() has not been called yet.");
    }

    if (publicKey_B.mod(fConstants.largePrime_N).equals(BigInteger.ZERO)) {
      throw new SRPAuthenticationFailedException("B%N == 0");
    }

    BigInteger SRP6_u = SRPUtils.calc_u(fPublicKey_A, publicKey_B);
    if (SRP6_u.mod(fConstants.largePrime_N).equals(BigInteger.ZERO)) {
      throw new SRPAuthenticationFailedException("u%N == 0");
    }

    // S = (B - 3(g^x))^(a + ux)
    BigInteger three_g_pow_x =
        fConstants.srp6Multiplier_k.multiply(
            fConstants.primitiveRoot_g.modPow(fPrivateKey_x, fConstants.largePrime_N));
    BigInteger B_minus_g_pow_x = publicKey_B.subtract(three_g_pow_x);
    BigInteger ux = SRP6_u.multiply(fPrivateKey_x);
    fCommonValue_S =
        B_minus_g_pow_x.modPow(fRandom_a.add(ux), fConstants.largePrime_N)
            .mod(fConstants.largePrime_N);
    fEvidenceValue_M1 = SRPUtils.calcM1(fPublicKey_A, publicKey_B, fCommonValue_S);

    // the MD5 output is the same as the AES key length
    fSessionKey_K = SRPUtils.hashToBytesMD5(fCommonValue_S);
  }
Example #7
0
  public void calculate_S() {
    S =
        B.subtract(k.multiply(g.modPow(x, N)))
            .modPow(a.add(u.multiply(x)), N); // S = (B - (k*g^x))^(a+ux)

    System.out.println("S in Client: " + S.toString());
  }
  /**
   * Certificate_Verify(証明書)を受け取ったときの動作をします。
   *
   * @param line クライアントから受信した文字列
   * @return クライアントの証明書の真偽
   * @author kinbara
   */
  private boolean recieveCertificateVerify(String line) {
    boolean cert_verify = false;
    // サーバー側のダイジェストのハッシュ値
    ListIterator listIte = netDigest.listIterator();
    String digest = "";
    while (listIte.hasNext()) {
      digest += listIte.next().toString();
    }
    digest = digest.substring(0, digest.indexOf("Certificate_Verify"));
    BigInteger digest1 = new BigInteger(this.getHash(digest), 16);
    // クライアントの公開鍵で復号
    BigInteger digest2 = new BigInteger(line.substring(line.indexOf(":") + 1), 16);
    try {
      X509 x509 = new X509("src/sglserver/conf/key/ca", "CAKeyStore", this.storePasswd);
      // TODO:(注意)ユーザーの公開鍵をpeerNameでCAKeyStoreに登録している場合のみ有効
      RSAPublicKey pk = x509.getRSAPublicKey(peerName);
      digest2 = digest2.modPow(pk.getPublicExponent(), pk.getModulus()); // 復号
      // b = a.modPow(s, n); → a mod n のs乗がbに代入される
      // pk.getPublicExponent()→公開指数
      // pk.getModulus()→pkのmod値
    } catch (Exception e) {

      e.printStackTrace();
    }
    if (digest1.compareTo(digest2) == 0) {
      System.out.println(socket.getRemoteSocketAddress() + "は、信頼できます。");
      cert_verify = true;
    } else {
      System.out.println(socket.getRemoteSocketAddress() + "は、危険です。");
    }
    return (cert_verify);
  }
 public int Decrypto(BigInteger c) {
   BigInteger nSquare = n.multiply(n);
   BigInteger Ans = c.modPow(lambda, nSquare);
   Ans = Ans.subtract(BigInteger.ONE).divide(n);
   Ans = Ans.remainder(n).multiply(nu).remainder(n);
   return Ans.intValue();
 }
Example #10
0
  public byte[] processBlock(byte[] var1, int var2, int var3) {
    if (this.key == null) {
      throw new IllegalStateException("RSA engine not initialised");
    } else {
      BigInteger var4 = this.core.convertInput(var1, var2, var3);
      BigInteger var16;
      if (this.key instanceof RSAPrivateCrtKeyParameters) {
        RSAPrivateCrtKeyParameters var5 = (RSAPrivateCrtKeyParameters) this.key;
        BigInteger var6 = var5.getPublicExponent();
        if (var6 != null) {
          BigInteger var7 = var5.getModulus();
          BigInteger var8 = ONE;
          BigInteger var9 = ONE;
          BigInteger var10 = var7.subtract(var9);
          SecureRandom var11 = this.random;
          BigInteger var12 = BigIntegers.createRandomInRange(var8, var10, var11);
          BigInteger var13 = var12.modPow(var6, var7).multiply(var4).mod(var7);
          BigInteger var14 = this.core.processBlock(var13);
          BigInteger var15 = var12.modInverse(var7);
          var16 = var14.multiply(var15).mod(var7);
        } else {
          var16 = this.core.processBlock(var4);
        }
      } else {
        var16 = this.core.processBlock(var4);
      }

      return this.core.convertOutput(var16);
    }
  }
  private static BigInteger calculateGenerator_FIPS186_3_Verifiable(
      Digest d, BigInteger p, BigInteger q, byte[] seed, int index) {
    // A.2.3 Verifiable Canonical Generation of the Generator g
    BigInteger e = p.subtract(ONE).divide(q);
    byte[] ggen = Hex.decode("6767656E");

    // 7. U = domain_parameter_seed || "ggen" || index || count.
    byte[] U = new byte[seed.length + ggen.length + 1 + 2];
    System.arraycopy(seed, 0, U, 0, seed.length);
    System.arraycopy(ggen, 0, U, seed.length, ggen.length);
    U[U.length - 3] = (byte) index;

    byte[] w = new byte[d.getDigestSize()];
    for (int count = 1; count < (1 << 16); ++count) {
      inc(U);
      hash(d, U, w);
      BigInteger W = new BigInteger(1, w);
      BigInteger g = W.modPow(e, p);
      if (g.compareTo(TWO) >= 0) {
        return g;
      }
    }

    return null;
  }
Example #12
0
  public void RSAEncrypt(int length, int modulus_size) throws RdesktopException {
    byte[] inr = new byte[length];
    // int outlength = 0;
    BigInteger mod = null;
    BigInteger exp = null;
    BigInteger x = null;

    this.reverse(this.exponent);
    this.reverse(this.modulus);
    System.arraycopy(this.client_random, 0, inr, 0, length);
    this.reverse(inr);

    if ((this.modulus[0] & 0x80) != 0) {
      byte[] temp = new byte[this.modulus.length + 1];
      System.arraycopy(this.modulus, 0, temp, 1, this.modulus.length);
      temp[0] = 0;
      mod = new BigInteger(temp);
    } else {
      mod = new BigInteger(this.modulus);
    }
    if ((this.exponent[0] & 0x80) != 0) {
      byte[] temp = new byte[this.exponent.length + 1];
      System.arraycopy(this.exponent, 0, temp, 1, this.exponent.length);
      temp[0] = 0;
      exp = new BigInteger(temp);
    } else {
      exp = new BigInteger(this.exponent);
    }
    if ((inr[0] & 0x80) != 0) {
      byte[] temp = new byte[inr.length + 1];
      System.arraycopy(inr, 0, temp, 1, inr.length);
      temp[0] = 0;
      x = new BigInteger(temp);
    } else {
      x = new BigInteger(inr);
    }

    BigInteger y = x.modPow(exp, mod);
    this.sec_crypted_random = y.toByteArray();

    if ((this.sec_crypted_random[0] & 0x80) != 0) {
      throw new RdesktopException("Wrong Sign! Expected positive Integer!");
    }

    if (this.sec_crypted_random.length > SEC_MAX_MODULUS_SIZE) {
      logger.warn("sec_crypted_random too big!"); /* FIXME */
    }
    this.reverse(this.sec_crypted_random);

    byte[] temp = new byte[SEC_MAX_MODULUS_SIZE];

    if (this.sec_crypted_random.length < modulus_size) {
      System.arraycopy(this.sec_crypted_random, 0, temp, 0, this.sec_crypted_random.length);
      for (int i = this.sec_crypted_random.length; i < temp.length; i++) {
        temp[i] = 0;
      }
      this.sec_crypted_random = temp;
    }
  }
 public static int generateN(int g, int p) {
   secret = generatePrime();
   BigInteger tmp;
   tmp = BigInteger.valueOf((long) g);
   long n =
       tmp.modPow(BigInteger.valueOf((long) secret), BigInteger.valueOf((long) p)).longValue();
   return (int) n;
 }
  public static int generateFinal(int p, int n) {
    BigInteger tmp;
    tmp = BigInteger.valueOf((long) n);
    long fin =
        tmp.modPow(BigInteger.valueOf((long) secret), BigInteger.valueOf((long) p)).longValue();

    return (int) fin;
  }
 public BigInteger Encrypto(int m, BigInteger n, BigInteger g) {
   int r = new Random().nextInt(10) + 3;
   BigInteger Ans = BigInteger.ZERO;
   BigInteger nSquare = n.multiply(n);
   Ans = g.modPow(BigInteger.valueOf(m), nSquare);
   Ans = Ans.multiply(BigInteger.valueOf(r).modPow(n, nSquare));
   Ans = Ans.remainder(nSquare);
   return Ans;
 }
 public void assertSRPConstants(SRPConstants.Parameters params, int bitLength) {
   Assert.assertNotNull(params.g);
   Assert.assertNotNull(params.N);
   Assert.assertEquals(bitLength, bitLength);
   Assert.assertEquals(bitLength / 8, params.byteLength);
   Assert.assertEquals(bitLength / 4, params.hexLength);
   BigInteger N = params.N;
   BigInteger g = params.g;
   // Each prime N is of the form 2*q + 1, with q also prime.
   BigInteger q = N.subtract(new BigInteger("1")).divide(new BigInteger("2"));
   // Check that g is a generator: the order of g is exactly 2*q (not 2, not q).
   Assert.assertFalse(new BigInteger("1").equals(g.modPow(new BigInteger("2"), N)));
   Assert.assertFalse(new BigInteger("1").equals(g.modPow(q, N)));
   Assert.assertTrue(new BigInteger("1").equals(g.modPow((N.subtract(new BigInteger("1"))), N)));
   // Even probable primality checking is too expensive to do here.
   // Assert.assertTrue(N.isProbablePrime(3));
   // Assert.assertTrue(q.isProbablePrime(3));
 }
Example #17
0
 /** Decrypts an RSA encrypted packet using our private key */
 public static ByteBuf decryptRSA(byte[] pData) {
   try {
     BigInteger bigInteger = new BigInteger(pData);
     byte[] decrypted = bigInteger.modPow(key, modulus).toByteArray();
     return Unpooled.wrappedBuffer(decrypted);
   } catch (Exception e) {
     return null;
   }
 }
Example #18
0
  public static boolean RabinMiller(BigInteger n, int precision) {

    BigInteger poverty = new BigInteger("0");
    BigInteger two = new BigInteger("2");
    BigInteger sum = new BigInteger("0");
    BigInteger x = new BigInteger("0");
    BigInteger factor = n.subtract(BigInteger.ONE);

    while (factor.mod(two).equals(BigInteger.ZERO)) {

      poverty = poverty.add(BigInteger.ONE);
      factor = factor.divide(two);
    }

    for (int i = 1; i <= 30; i++) {

      SecureRandom seed = new SecureRandom();
      BigInteger base = new BigInteger(n.bitLength(), seed);

      while ((base.compareTo(n.subtract(BigInteger.ONE)) >= 0)
          || base.compareTo(BigInteger.ONE) <= 0) {
        base = new BigInteger(n.bitLength(), seed);
      }

      x = base.modPow(factor, n);

      if (x.equals(BigInteger.ONE) || x.equals(n.subtract(BigInteger.ONE))) continue;

      sum = sum.add(BigInteger.ONE);

      while ((sum.compareTo(poverty) < 0) && !(x.equals(n.subtract(BigInteger.ONE)))) {

        x = x.modPow(two, n);

        if (x.equals(BigInteger.ONE)) return false;
        sum = sum.add(BigInteger.ONE);
      }

      if (!(x.equals(n.subtract(BigInteger.ONE)))) return false;
      if (sum.equals(poverty)) return false;
    }

    return true;
  }
Example #19
0
 String encrypt(String password) {
   BigInteger data = pkcs1pad2(password.getBytes(charset), (modulus.bitLength() + 7) >> 3);
   BigInteger d2 = data.modPow(exponent, modulus);
   String dataHex = d2.toString(16);
   if ((dataHex.length() & 1) == 1) {
     dataHex = "0" + dataHex;
   }
   byte[] encrypted = hexStringToByteArray(dataHex);
   return Base64.encodeBase64String(encrypted);
 }
 /**
  * Compute a cube root of v (mod p) where p = 4 (mod 9).
  *
  * @return a cube root of v (mod p) if one exists, or null otherwise.
  * @exception IllegalArgumentException if the size p of the underlying finite field does not
  *     satisfy p = 4 (mod 9).
  */
 public BigInteger cbrt(BigInteger v) {
   if (p.mod(_9).intValue() != 4) {
     throw new IllegalArgumentException(
         "This implementation is optimized for, and only works with, prime fields GF(p) where p = 4 (mod 9)");
   }
   if (v.signum() == 0) {
     return _0;
   }
   BigInteger r = v.modPow(cbrtExponent, p); // r = v^{(2p + 1)/9}
   return r.multiply(r).multiply(r).subtract(v).mod(p).signum() == 0 ? r : null;
 }
Example #21
0
  public RSA(Random random) {
    savedRandom = random;

    p = getPrime(random); // p and q are arbitrary large primes
    q = getPrime(random);
    n = p.multiply(q);
    phiN = (p.subtract(ONE)).multiply(q.subtract(ONE));

    S = getPrime(random); // s is an arbitrary secret; we'll use a prime
    V = S.modPow(new BigInteger("2"), n);
  }
Example #22
0
  @Test
  public void testPow() {

    BigInteger x = BigInteger.valueOf(Integer.MAX_VALUE);
    BigInteger y = BigInteger.valueOf(1000);

    BigInteger result1 = x.modPow(x, y);
    BigInteger result2 = pow(x, y);
    System.out.println(result1);
    System.out.println(result2);
  }
  /**
   * Returns modulo calculation phase
   *
   * @param mod BigInteger modulo
   * @return StringBuilder modulo_phase
   */
  public StringBuilder getModulo(BigInteger mod) {
    StringBuilder s = new StringBuilder();
    StringBuilder begin = new StringBuilder();
    String[] p = powerDivison(exponent).toString().split("\\+");
    BigInteger help = new BigInteger("0");

    int a = 0;
    for (int i = 0; i < p.length; i++) {
      if (new BigInteger(p[i]).compareTo(BigInteger.ONE) < 1) {
        s.append(number);
        if (i < p.length - 1) {
          s.append(kongru);
          begin.append(s);
        }
      } else {
        help = number.modPow(new BigInteger(p[i]), mod);
        s.append(help);
        begin.append(help);
        if (i < p.length - 1) {
          s.append(kongru);
          begin.append(kongru);
        }

        a = i;
        for (int j = i; j < p.length; j++) {
          if (j < p.length - 1) {
            s.append(help);
            // s.append("^");
            s.append(
                sc.superScript(new BigInteger(p[j + 1]).divide(new BigInteger(p[a])).toString()));
            if (j + 1 < p.length - 1) {
              s.append(kongru);
            }
          }
        }
        if (i < p.length - 1) {
          s.append("\n " + times);
          s.append(begin);
        }
      }
    }

    s.append("\n " + times);
    BigInteger answer = BigInteger.ONE;
    String[] v = begin.toString().split(kongru);
    for (int i = 0; i < v.length; i++) {
      answer = answer.multiply(new BigInteger(v[i]));
    }

    s.append(answer.mod(mod));
    s.append("(mod " + mod + ")");
    return s;
  }
Example #24
0
 public void dbh(BigInteger biginteger, BigInteger biginteger1) {
   int i = dak;
   dak = 0;
   byte abyte0[] = new byte[i];
   dbg(abyte0, 0, i);
   BigInteger biginteger2 = new BigInteger(abyte0);
   BigInteger biginteger3 = biginteger2.modPow(biginteger, biginteger1);
   byte abyte1[] = biginteger3.toByteArray();
   dak = 0;
   dan(abyte1.length);
   dbc(abyte1, 0, abyte1.length);
 }
  public String encrypt(String text) {
    BigInteger T, C, N;
    T = new BigInteger(text); // here goes the number to be crypted (text).
    N = size;

    // T = T.pow(key.intValue()); // FIXA!!!!
    // C = T.mod(N);

    C = T.modPow(key, N);

    return C.toString();
  }
Example #26
0
  public static String decrypt(BigInteger[] cipherMessage, BigInteger pq, BigInteger d) {
    // decrypt with: message.modPow(d, n);
    String decodedMessage = "";

    for (int i = 0; i < cipherMessage.length; i++) {
      BigInteger c = cipherMessage[i];
      BigInteger m = c.modPow(d, pq);
      decodedMessage += (char) (m.intValue());
    }

    return decodedMessage;
  }
Example #27
0
  public static BigInteger[] encrypt(String message, BigInteger pq, BigInteger e) {
    // Encyrpt with:  message.modPow(e, n);
    BigInteger[] cipherMessage = new BigInteger[message.length()];

    for (int i = 0; i < message.length(); i++) {
      BigInteger m = new BigInteger(((int) message.charAt(i)) + "");
      BigInteger c = m.modPow(e, pq);
      cipherMessage[i] = c;
    }

    return cipherMessage;
  }
  private static BigInteger calculateGenerator_FIPS186_2(
      BigInteger p, BigInteger q, SecureRandom r) {
    BigInteger e = p.subtract(ONE).divide(q);
    BigInteger pSub2 = p.subtract(TWO);

    for (; ; ) {
      BigInteger h = BigIntegers.createRandomInRange(TWO, pSub2, r);
      BigInteger g = h.modPow(e, p);
      if (g.bitLength() > 1) {
        return g;
      }
    }
  }
Example #29
0
 public String getSharedSecret(String peerPubKey) {
   BigInteger primeInt = new BigInteger(1, decodeB64(PRIME));
   BigInteger peerPubInt = new BigInteger(1, decodeB64(peerPubKey));
   BigInteger shareInt = peerPubInt.modPow(_privateInt, primeInt);
   try {
     MessageDigest md = MessageDigest.getInstance("SHA-256");
     byte[] hashed = md.digest(getBytes(shareInt));
     return encodeB64(hashed);
   } catch (NoSuchAlgorithmException e) {
     logger.debug("Algorithm for DH1080 shared secret hashing not available", e);
   }
   return null;
 }
  /**
   * Client_Key_Exchangeを受け取ったときの動作をします。
   *
   * @param line クライアントから受信した文字列
   * @throws CertificateException
   * @throws IOException
   * @throws KeyStoreException
   * @throws NoSuchAlgorithmException
   * @throws UnrecoverableKeyException
   * @author kinbara
   */
  private void recieveClientKeyExchange(String line)
      throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
          UnrecoverableKeyException {

    X509 x509 = new X509("src/sglserver/conf/key/ca", "CAKeyStore", this.storePasswd);
    RSAPrivateKey sk = x509.getRSAPrivateKey("server", this.keyPasswd);
    // 暗号化されたプリマスターシークレットの抽出
    line = line.substring(line.indexOf(":") + 1);
    BigInteger preCipher = new BigInteger(line, 16);
    // プリマスターシークレットを復号
    preMastarSecret = preCipher.modPow(sk.getPrivateExponent(), sk.getModulus());
    // (事前共有鍵)=(秘密鍵). modPow((s乗:すなわちaのs乗),(元:すなわちg))
    // b = a.modPow(s, n); a mod n のs乗がbに代入される
  }