private static void concat(byte[] src, byte[] dst, int start, int len) {
   if (src.length == 0) {
     return;
   }
   int loop = len / src.length;
   int off, i;
   for (i = 0, off = 0; i < loop; i++, off += src.length)
     System.arraycopy(src, 0, dst, off + start, src.length);
   System.arraycopy(src, 0, dst, off + start, len - off);
 }
Example #2
0
  public boolean verify(byte[] sig) throws Exception {
    int i = 0;
    int j = 0;
    byte[] tmp;

    if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0) {
      j =
          ((sig[i++] << 24) & 0xff000000)
              | ((sig[i++] << 16) & 0x00ff0000)
              | ((sig[i++] << 8) & 0x0000ff00)
              | ((sig[i++]) & 0x000000ff);
      i += j;
      j =
          ((sig[i++] << 24) & 0xff000000)
              | ((sig[i++] << 16) & 0x00ff0000)
              | ((sig[i++] << 8) & 0x0000ff00)
              | ((sig[i++]) & 0x000000ff);
      tmp = new byte[j];
      System.arraycopy(sig, i, tmp, 0, j);
      sig = tmp;
    }

    // ASN.1
    int frst = ((sig[0] & 0x80) != 0 ? 1 : 0);
    int scnd = ((sig[20] & 0x80) != 0 ? 1 : 0);
    // System.err.println("frst: "+frst+", scnd: "+scnd);

    int length = sig.length + 6 + frst + scnd;
    tmp = new byte[length];
    tmp[0] = (byte) 0x30;
    tmp[1] = (byte) 0x2c;
    tmp[1] += frst;
    tmp[1] += scnd;
    tmp[2] = (byte) 0x02;
    tmp[3] = (byte) 0x14;
    tmp[3] += frst;
    System.arraycopy(sig, 0, tmp, 4 + frst, 20);
    tmp[4 + tmp[3]] = (byte) 0x02;
    tmp[5 + tmp[3]] = (byte) 0x14;
    tmp[5 + tmp[3]] += scnd;
    System.arraycopy(sig, 20, tmp, 6 + tmp[3] + scnd, 20);
    sig = tmp;

    /*
        tmp=new byte[sig.length+6];
        tmp[0]=(byte)0x30; tmp[1]=(byte)0x2c;
        tmp[2]=(byte)0x02; tmp[3]=(byte)0x14;
        System.arraycopy(sig, 0, tmp, 4, 20);
        tmp[24]=(byte)0x02; tmp[25]=(byte)0x14;
        System.arraycopy(sig, 20, tmp, 26, 20); sig=tmp;
    */
    return signature.verify(sig);
  }
Example #3
0
  private static void permissionCheck() {
    SecurityManager sec = System.getSecurityManager();

    if (sec != null) {
      sec.checkPermission(new RuntimePermission("useKeychainStore"));
    }
  }
Example #4
0
  public byte[] sign() throws Exception {
    byte[] sig = signature.sign();
    /*
    System.err.print("sign["+sig.length+"] ");
    for(int i=0; i<sig.length;i++){
    System.err.print(Integer.toHexString(sig[i]&0xff)+":");
    }
    System.err.println("");
    */
    // sig is in ASN.1
    // SEQUENCE::={ r INTEGER, s INTEGER }
    int len = 0;
    int index = 3;
    len = sig[index++] & 0xff;
    // System.err.println("! len="+len);
    byte[] r = new byte[len];
    System.arraycopy(sig, index, r, 0, r.length);
    index = index + len + 1;
    len = sig[index++] & 0xff;
    // System.err.println("!! len="+len);
    byte[] s = new byte[len];
    System.arraycopy(sig, index, s, 0, s.length);

    byte[] result = new byte[40];

    // result must be 40 bytes, but length of r and s may not be 20 bytes

    System.arraycopy(
        r,
        (r.length > 20) ? 1 : 0,
        result,
        (r.length > 20) ? 0 : 20 - r.length,
        (r.length > 20) ? 20 : r.length);
    System.arraycopy(
        s,
        (s.length > 20) ? 1 : 0,
        result,
        (s.length > 20) ? 20 : 40 - s.length,
        (s.length > 20) ? 20 : s.length);

    //  System.arraycopy(sig, (sig[3]==20?4:5), result, 0, 20);
    //  System.arraycopy(sig, sig.length-20, result, 20, 20);

    return result;
  }
Example #5
0
  // Reads the contents of the passed file into a string
  public String getContents(File file) {
    StringBuilder result = new StringBuilder();

    try {
      BufferedReader input = new BufferedReader(new FileReader(file));
      String nextLine = new String();

      while ((nextLine = input.readLine()) != null) {
        result.append(nextLine);
        result.append(System.getProperty("line.separator"));
      }

      input.close();
    } catch (Exception e) {
      System.out.println("Encryption/Decryption File Error: " + e);
    }

    return result.toString();
  }
Example #6
0
  /**
   * Generate the RSA key pairs for encrypting the DES file key
   *
   * @throws InvalidKeySpecException
   */
  private void genRSAKeys() throws InvalidKeySpecException {
    try {
      KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");

      SecureRandom random = new SecureRandom();
      String seed = ((Long) System.currentTimeMillis()).toString();
      random.setSeed(seed.getBytes());
      keygen.initialize(1024, random);

      KeyPair kp = keygen.generateKeyPair();
      publicKey = (RSAPublicKey) kp.getPublic();
      privateKey = (RSAPrivateKey) kp.getPrivate();

      // System.out.println("RSA public key: " + publicKey);
      // System.out.println("RSA private key: " + privateKey);

    } catch (NoSuchAlgorithmException e) {
      System.out.println("Failed to generate RSA key pairs!\n" + e.toString());
    }
  }
Example #7
0
 private int implDoFinal(byte[] out, int outOfs, int outLen)
     throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
   int requiredOutLen = doFinalLength(0);
   if (outLen < requiredOutLen) {
     throw new ShortBufferException();
   }
   try {
     ensureInitialized();
     int k = 0;
     if (encrypt) {
       if (paddingObj != null) {
         int actualPadLen = paddingObj.setPaddingBytes(padBuffer, requiredOutLen - bytesBuffered);
         k =
             token.p11.C_EncryptUpdate(
                 session.id(), 0, padBuffer, 0, actualPadLen, 0, out, outOfs, outLen);
       }
       k += token.p11.C_EncryptFinal(session.id(), 0, out, (outOfs + k), (outLen - k));
     } else {
       if (paddingObj != null) {
         if (padBufferLen != 0) {
           k =
               token.p11.C_DecryptUpdate(
                   session.id(), 0, padBuffer, 0, padBufferLen, 0, padBuffer, 0, padBuffer.length);
         }
         k += token.p11.C_DecryptFinal(session.id(), 0, padBuffer, k, padBuffer.length - k);
         int actualPadLen = paddingObj.unpad(padBuffer, k);
         k -= actualPadLen;
         System.arraycopy(padBuffer, 0, out, outOfs, k);
       } else {
         k = token.p11.C_DecryptFinal(session.id(), 0, out, outOfs, outLen);
       }
     }
     return k;
   } catch (PKCS11Exception e) {
     handleException(e);
     throw new ProviderException("doFinal() failed", e);
   } finally {
     reset();
   }
 }
Example #8
0
  public boolean verify(byte[] sig) throws Exception {
    int i = 0;
    int j = 0;
    byte[] tmp;

    if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0) {
      j =
          ((sig[i++] << 24) & 0xff000000)
              | ((sig[i++] << 16) & 0x00ff0000)
              | ((sig[i++] << 8) & 0x0000ff00)
              | ((sig[i++]) & 0x000000ff);
      i += j;
      j =
          ((sig[i++] << 24) & 0xff000000)
              | ((sig[i++] << 16) & 0x00ff0000)
              | ((sig[i++] << 8) & 0x0000ff00)
              | ((sig[i++]) & 0x000000ff);
      tmp = new byte[j];
      System.arraycopy(sig, i, tmp, 0, j);
      sig = tmp;
    }
    // System.err.println("j="+j+" "+Integer.toHexString(sig[0]&0xff));
    return signature.verify(sig);
  }
  // Uses supplied hash algorithm
  static byte[] derive(
      char[] chars, byte[] salt, int ic, int n, int type, String hashAlgo, int blockLength) {

    // Add in trailing NULL terminator.  Special case:
    // no terminator if password is "\0".
    int length = chars.length * 2;
    if (length == 2 && chars[0] == 0) {
      chars = new char[0];
      length = 0;
    } else {
      length += 2;
    }

    byte[] passwd = new byte[length];
    for (int i = 0, j = 0; i < chars.length; i++, j += 2) {
      passwd[j] = (byte) ((chars[i] >>> 8) & 0xFF);
      passwd[j + 1] = (byte) (chars[i] & 0xFF);
    }
    byte[] key = new byte[n];

    try {
      MessageDigest sha = MessageDigest.getInstance(hashAlgo);

      int v = blockLength;
      int u = sha.getDigestLength();
      int c = roundup(n, u) / u;
      byte[] D = new byte[v];
      int s = roundup(salt.length, v);
      int p = roundup(passwd.length, v);
      byte[] I = new byte[s + p];

      Arrays.fill(D, (byte) type);
      concat(salt, I, 0, s);
      concat(passwd, I, s, p);

      byte[] Ai;
      byte[] B = new byte[v];
      byte[] tmp = new byte[v];

      int i = 0;
      for (; ; i++, n -= u) {
        sha.update(D);
        sha.update(I);
        Ai = sha.digest();
        for (int r = 1; r < ic; r++) Ai = sha.digest(Ai);
        System.arraycopy(Ai, 0, key, u * i, Math.min(n, u));
        if (i + 1 == c) break;
        concat(Ai, B, 0, B.length);
        BigInteger B1;
        B1 = new BigInteger(1, B).add(BigInteger.ONE);

        for (int j = 0; j < I.length; j += v) {
          BigInteger Ij;
          int trunc;

          if (tmp.length != v) tmp = new byte[v];
          System.arraycopy(I, j, tmp, 0, v);
          Ij = new BigInteger(1, tmp);
          Ij = Ij.add(B1);
          tmp = Ij.toByteArray();
          trunc = tmp.length - v;
          if (trunc >= 0) {
            System.arraycopy(tmp, trunc, I, j, v);
          } else if (trunc < 0) {
            Arrays.fill(I, j, j + (-trunc), (byte) 0);
            System.arraycopy(tmp, 0, I, j + (-trunc), tmp.length);
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException("internal error: " + e);
    }
    return key;
  }
Example #10
0
 private final void bufferInputBytes(byte[] in, int inOfs, int len) {
   System.arraycopy(in, inOfs, padBuffer, padBufferLen, len);
   padBufferLen += len;
   bytesBuffered += len;
 }