Ejemplo n.º 1
0
  private void Encrypter(String data) throws Exception {

    // Security.addProvider(new MainActivity().BouncyCastleProvider());

    byte[] input = data.getBytes();
    byte[] keyBytes = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};

    int keySize = keyBytes.length;
    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

    mTxtInput.setText(new String(data));
    // System.out.println(new String(input));

    // encryption pass
    cipher.init(Cipher.ENCRYPT_MODE, key);

    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);

    // System.out.println(new String(cipherText));
    // System.out.println(ctLength);

    mTxtCipher.setText(new String(cipherText));
    mTxtCtLenght.setText(String.valueOf(ctLength));
    // decryption pass
    String x = new String(cipherText);
  }
Ejemplo n.º 2
0
  public static byte[] encryptDataBytes(PublicKey publicKey, byte[] data) {
    try {
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());

      cipher.init(1, publicKey);
      int blockSize = cipher.getBlockSize();
      int outputSize = cipher.getOutputSize(data.length);
      int leavedSize = data.length % blockSize;
      int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;

      byte[] raw = new byte[outputSize * blocksSize];
      int i = 0;
      while (data.length - i * blockSize > 0) {
        if (data.length - i * blockSize > blockSize)
          cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
        else {
          cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
        }

        i++;
      }
      return raw;
    } catch (Exception e) {
      logger.error(e.getMessage());
      return null;
    }
  }
Ejemplo n.º 3
0
  private static void testEncryptDecryptLong(
      Cipher c, Cipher d, String string, long key, long value)
      throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
    byte[] data = new byte[3 + 8 + 8];
    byte[] output = new byte[c.getOutputSize(data.length)];
    byte[] result = new byte[3 + 8 + 8];

    byte[] salt = string.getBytes();

    System.arraycopy(salt, 0, data, 0, salt.length);

    longToByteArray2(key, data, 3);
    longToByteArray2(value, data, 11);

    c.doFinal(data, 0, data.length, output);
    d.doFinal(output, 0, output.length, result);

    System.out.println("in: " + toHex(data));
    System.out.println("enc: " + toHex(output));
    System.out.println("dec: " + toHex(result));

    for (int i = 0; i < data.length; i++) {
      if (data[i] != result[i]) throw new IllegalStateException("darn gosh");
    }
  }
Ejemplo n.º 4
0
  public static void crypt(String inFilename, String outFilename, int mode) {
    InputStream in = null;
    OutputStream out = null;
    ObjectInputStream keyin = null;
    try {
      in = new FileInputStream(inFilename);
      out = new FileOutputStream(outFilename);
      keyin = new ObjectInputStream(new FileInputStream(keyFilename));
      // 获取到密钥
      Key key = (Key) keyin.readObject();
      // 使用AES算法获取密码对象
      Cipher cipher = Cipher.getInstance("AES");
      // 通过设置模式和密钥来初始化
      cipher.init(mode, key);

      // 获取密码块大小,16
      int blockSize = cipher.getBlockSize();
      // 该密码块对应的输出缓存区大小,用于存放密码对象输出的数据块
      int outputSize = cipher.getOutputSize(blockSize);
      byte[] inBytes = new byte[blockSize];
      byte[] outBytes = new byte[outputSize];
      int length = 0;

      boolean more = true;
      while (more) {
        length = in.read(inBytes);
        // 如果能读到blockSize大小的块
        if (length == blockSize) {
          // 数据块存入outBytes
          int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
          out.write(outBytes, 0, outLength);
        } else {
          more = false;
        }
      }
      // 如果最后一个输入数据块的字节数小于blockSize,剩下的字节将会自动填充
      if (length > 0) {
        outBytes = cipher.doFinal(inBytes, 0, length);
      } else {
        outBytes = cipher.doFinal();
      }
      out.write(outBytes);

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (GeneralSecurityException e) {
      e.printStackTrace();
    } finally {
      Closer.close(in);
      Closer.close(out);
      Closer.close(keyin);
    }
  }
  public static void main(String args[]) throws Exception {
    boolean failedOnce = false;
    Exception failedReason = null;

    byte[] keyBytes = new byte[8];
    random.nextBytes(keyBytes);
    SecretKey key = new SecretKeySpec(keyBytes, "DES");

    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding", "SunJCE");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    /*
     * Iterate through various sizes to make sure that the code does empty
     * blocks, single partial blocks, 1 full block, full + partial blocks,
     * multiple full blocks, etc. 5 blocks (using DES) is probably overkill
     * but will feel more confident the fix isn't breaking anything.
     */
    System.out.println("Output test results for every " + outputFrequency + " tests...");

    for (int size = 0; size <= testSizes; size++) {
      boolean output = (size % outputFrequency) == 0;
      if (output) {
        System.out.print("\nTesting buffer size: " + size + ":");
      }

      int outSize = cipher.getOutputSize(size);

      try {
        encrypt(
            cipher,
            size,
            ByteBuffer.allocate(size),
            ByteBuffer.allocate(outSize),
            ByteBuffer.allocateDirect(size),
            ByteBuffer.allocateDirect(outSize),
            output);
      } catch (Exception e) {
        System.out.print("\n Failed with size " + size);
        failedOnce = true;
        failedReason = e;

        // If we got an exception, let's be safe for future
        // testing and reset the cipher to a known good state.
        cipher.init(Cipher.ENCRYPT_MODE, key);
      }
    }
    if (failedOnce) {
      throw failedReason;
    }
    System.out.println("\nTest Passed...");
  }
Ejemplo n.º 6
0
  @Override
  public void setup() {
    try {
      algo = javax.crypto.Cipher.getInstance("AES/CFB8/NoPadding");
      java.security.Key key = new SecretKeySpec(publicKey, 0, 16, "AES");
      algo.init(javax.crypto.Cipher.ENCRYPT_MODE, key);
    } catch (Exception e) {
      System.out.println(e);
    }

    inAlgoBuffer = new byte[algo.getBlockSize()]; // always 0x00's
    outAlgoBufferIx = algo.getOutputSize(algo.getBlockSize());
    outAlgoBuffer = new byte[outAlgoBufferIx]; // output of encryption
  }
Ejemplo n.º 7
0
  private static void crypt(InputStream input, OutputStream out, Cipher cipher)
      throws IOException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
    int blockSize = cipher.getBlockSize();
    int outputSize = cipher.getOutputSize(blockSize);

    int inLength;
    byte[] inBytes = new byte[blockSize];
    byte[] outBytes = new byte[outputSize];
    while ((inLength = IOUtils.read(input, inBytes)) != 0) {
      int outLength = cipher.update(inBytes, 0, inLength, outBytes);
      out.write(outBytes, 0, outLength);
    }
    IOUtils.write(cipher.doFinal(), out);
  }
Ejemplo n.º 8
0
  private void testGCMParameterSpecWithMultipleUpdates(
      byte[] K, byte[] N, byte[] A, byte[] P, byte[] C) throws Exception {
    Cipher eax = Cipher.getInstance("AES/EAX/NoPadding", "BC");
    SecretKeySpec key = new SecretKeySpec(K, "AES");
    SecureRandom random = new SecureRandom();

    // GCMParameterSpec mapped to AEADParameters and overrides default MAC
    // size
    GCMParameterSpec spec = new GCMParameterSpec(128, N);

    for (int i = 900; i != 1024; i++) {
      byte[] message = new byte[i];

      random.nextBytes(message);

      eax.init(Cipher.ENCRYPT_MODE, key, spec);

      byte[] out = new byte[eax.getOutputSize(i)];

      int offSet = 0;

      int count;
      for (count = 0; count < i / 21; count++) {
        offSet += eax.update(message, count * 21, 21, out, offSet);
      }

      offSet += eax.doFinal(message, count * 21, i - (count * 21), out, offSet);

      byte[] dec = new byte[i];
      int len = offSet;

      eax.init(Cipher.DECRYPT_MODE, key, spec);

      offSet = 0;
      for (count = 0; count < len / 10; count++) {
        offSet += eax.update(out, count * 10, 10, dec, offSet);
      }

      offSet += eax.doFinal(out, count * 10, len - (count * 10), dec, offSet);

      if (!Arrays.areEqual(message, dec) || offSet != message.length) {
        fail("message mismatch");
      }
    }
  }
Ejemplo n.º 9
0
  private void Decryptor(byte[] cipherText) throws Exception {

    byte[] keyBytes = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};

    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
    int keySize = keyBytes.length;
    int x = cipherText.length;

    // decryption pass
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] plainText = new byte[cipher.getOutputSize(x)];
    int ptLength = cipher.update(cipherText, 0, x, plainText, 0);
    ptLength += cipher.doFinal(plainText, ptLength);

    mTxtPlainText.setText(new String(plainText));
    // mTxtPtLength.setText(String.valueOf(ptLength));
  }
Ejemplo n.º 10
0
  /**
   * 加密
   *
   * @param key 加密的密钥
   * @param data 待加密的明文数据
   * @return 加密后的数据
   * @throws Exception
   */
  public static byte[] encrypt(Key key, byte[] data) throws Exception {

    try {

      Cipher cipher =
          Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());

      cipher.init(Cipher.ENCRYPT_MODE, key);

      int blockSize = cipher.getBlockSize(); // 获得加密块大小,如:加密前数据为128个byte,而key_size=1024
      // 加密块大小为127
      // byte,加密后为128个byte;因此共有2个加密块,第一个127
      // byte第二个为1个byte

      int outputSize = cipher.getOutputSize(data.length); // 获得加密块加密后块大小

      int leavedSize = data.length % blockSize;

      int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;

      byte[] raw = new byte[outputSize * blocksSize];

      int i = 0;

      while (data.length - i * blockSize > 0) {

        if (data.length - i * blockSize > blockSize)
          cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
        else cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);

        // 这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法。

        i++;
      }

      return raw;

    } catch (Exception e) {

      throw new Exception(e.getMessage());
    }
  }
Ejemplo n.º 11
0
  /**
   * Uses a cipher to transform the bytes in an input stream and sends the transformed bytes to an
   * output stream.
   *
   * @param in the input stream
   * @param out the output stream
   * @param cipher the cipher that transforms the bytes
   */
  public static void crypt(InputStream in, OutputStream out, Cipher cipher)
      throws IOException, GeneralSecurityException {
    int blockSize = cipher.getBlockSize();
    int outputSize = cipher.getOutputSize(blockSize);
    byte[] inBytes = new byte[blockSize];
    byte[] outBytes = new byte[outputSize];

    int inLength = 0;
    ;
    boolean more = true;
    while (more) {
      inLength = in.read(inBytes);
      if (inLength == blockSize) {
        int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
        out.write(outBytes, 0, outLength);
      } else more = false;
    }
    if (inLength > 0) outBytes = cipher.doFinal(inBytes, 0, inLength);
    else outBytes = cipher.doFinal();
    out.write(outBytes);
  }
Ejemplo n.º 12
0
  /**
   * Decrypts a given byte stream using the AES cipher, CBC mode, and PKCS5 Padding algorithms.
   *
   * @param input - Bytes to be decrypted
   * @param key - Symmetric key to decrypt
   * @param iv - Initialization vector
   * @return decrypted byte stream
   * @throws NoSuchAlgorithmException
   * @throws NoSuchPaddingException
   * @throws InvalidKeyException
   * @throws InvalidAlgorithmParameterException
   * @throws ShortBufferException
   * @throws IllegalBlockSizeException
   * @throws BadPaddingException
   * @throws UnsupportedEncodingException
   */
  public static byte[] AESCBCdecrypt(byte[] input, Key key, byte[] iv)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException,
          BadPaddingException, UnsupportedEncodingException {
    int plaintext_len;
    byte[] keyBytes, plaintext;
    SecretKeySpec keySpec;
    IvParameterSpec ivSpec;
    Cipher cipher;

    keyBytes = key.getBytes();
    keySpec = new SecretKeySpec(keyBytes, "AES");
    ivSpec = new IvParameterSpec(iv);
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    plaintext = new byte[cipher.getOutputSize(input.length)];

    plaintext_len = cipher.update(input, 0, input.length, plaintext, 0);
    plaintext_len += cipher.doFinal(plaintext, plaintext_len);
    return plaintext;
  }
Ejemplo n.º 13
0
  /**
   * * 加密 *
   *
   * @param key 加密的密钥 *
   * @param data 待加密的明文数据 *
   * @return 加密后的数据 *
   * @throws Exception
   */
  public static byte[] encryptByJs(String publicKey, byte[] data) throws Exception {
    try {
      // 字符串转key
      byte[] keyBytes = Base64Utils.decode(publicKey);
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      RSAPublicKey publicK = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);

      Cipher cipher =
          Cipher.getInstance(
              KEY_ALGORITHM, new org.bouncycastle.jce.provider.BouncyCastleProvider());
      cipher.init(Cipher.ENCRYPT_MODE, publicK);
      int blockSize = cipher.getBlockSize(); // 获得加密块大小,如:加密前数据为128个byte,而key_size=1024
      // 加密块大小为127
      // byte,加密后为128个byte;因此共有2个加密块,第一个127
      // byte第二个为1个byte
      int outputSize = cipher.getOutputSize(data.length); // 获得加密块加密后块大小
      int leavedSize = data.length % blockSize;
      int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
      byte[] raw = new byte[outputSize * blocksSize];
      int i = 0;
      while (data.length - i * blockSize > 0) {
        if (data.length - i * blockSize > blockSize)
          cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
        else cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
        // 这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到
        // ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了
        // OutputSize所以只好用dofinal方法。

        i++;
      }
      return raw;
    } catch (Exception e) {
      throw new Exception(ExceptionUtil.getStackTraceAsString(e));
    }
  }
Ejemplo n.º 14
0
  public void prepare() {
    try {
      System.out.println(
          "\nalgorithm="
              + algorithm
              + ", mode="
              + mode
              + ", paddingStr="
              + paddingStr
              + ", msgSize="
              + msgSize
              + ", keySize="
              + keySize
              + ", noReinit="
              + noReinit
              + ", checkOutput="
              + checkOutput
              + ", encInputOffset="
              + encInputOffset
              + ", encOutputOffset="
              + encOutputOffset
              + ", decOutputOffset="
              + decOutputOffset
              + ", lastChunkSize="
              + lastChunkSize);

      if (encInputOffset % ALIGN != 0
          || encOutputOffset % ALIGN != 0
          || decOutputOffset % ALIGN != 0) testingMisalignment = true;

      int keyLenBytes = (keySize == 0 ? 16 : keySize / 8);
      byte keyBytes[] = new byte[keyLenBytes];
      if (keySize == 128)
        keyBytes = new byte[] {-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7};
      else random.nextBytes(keyBytes);

      key = new SecretKeySpec(keyBytes, algorithm);
      if (threadId == 0) {
        System.out.println(
            "Algorithm: " + key.getAlgorithm() + "(" + key.getEncoded().length * 8 + "bit)");
      }

      cipher = Cipher.getInstance(algorithm + "/" + mode + "/" + paddingStr, "SunJCE");
      dCipher = Cipher.getInstance(algorithm + "/" + mode + "/" + paddingStr, "SunJCE");

      if (mode.equals("CBC")) {
        int ivLen = (algorithm.equals("AES") ? 16 : algorithm.equals("DES") ? 8 : 0);
        IvParameterSpec initVector = new IvParameterSpec(new byte[ivLen]);
        cipher.init(Cipher.ENCRYPT_MODE, key, initVector);
      } else {
        algParams = cipher.getParameters();
        cipher.init(Cipher.ENCRYPT_MODE, key, algParams);
      }
      algParams = cipher.getParameters();
      dCipher.init(Cipher.DECRYPT_MODE, key, algParams);
      if (threadId == 0) {
        childShowCipher();
      }

      inputLength = msgSize + encInputOffset;
      if (testingMisalignment) {
        encodeLength = cipher.getOutputSize(msgSize - lastChunkSize) + encOutputOffset;
        encodeLength += cipher.getOutputSize(lastChunkSize);
        decodeLength = dCipher.getOutputSize(encodeLength - lastChunkSize) + decOutputOffset;
        decodeLength += dCipher.getOutputSize(lastChunkSize);
      } else {
        encodeLength = cipher.getOutputSize(msgSize) + encOutputOffset;
        decodeLength = dCipher.getOutputSize(encodeLength) + decOutputOffset;
      }

      input = new byte[inputLength];
      for (int i = encInputOffset, j = 0; i < inputLength; i++, j++) {
        input[i] = (byte) (j & 0xff);
      }

      // do one encode and decode in preparation
      encode = new byte[encodeLength];
      decode = new byte[decodeLength];
      if (testingMisalignment) {
        decodeMsgSize =
            cipher.update(
                input, encInputOffset, (msgSize - lastChunkSize), encode, encOutputOffset);
        decodeMsgSize +=
            cipher.doFinal(
                input,
                (encInputOffset + msgSize - lastChunkSize),
                lastChunkSize,
                encode,
                (encOutputOffset + decodeMsgSize));

        int tempSize =
            dCipher.update(
                encode, encOutputOffset, (decodeMsgSize - lastChunkSize), decode, decOutputOffset);
        dCipher.doFinal(
            encode,
            (encOutputOffset + decodeMsgSize - lastChunkSize),
            lastChunkSize,
            decode,
            (decOutputOffset + tempSize));
      } else {
        decodeMsgSize = cipher.doFinal(input, encInputOffset, msgSize, encode, encOutputOffset);
        dCipher.doFinal(encode, encOutputOffset, decodeMsgSize, decode, decOutputOffset);
      }
      if (checkOutput) {
        expectedEncode = (byte[]) encode.clone();
        expectedDecode = (byte[]) decode.clone();
        showArray(key.getEncoded(), "key:    ");
        showArray(input, "input:  ");
        showArray(encode, "encode: ");
        showArray(decode, "decode: ");
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Ejemplo n.º 15
0
  private void testGP(int size, int privateValueSize, BigInteger g, BigInteger p) throws Exception {
    DHParameterSpec elParams = new DHParameterSpec(p, g, privateValueSize);
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ElGamal", "BC");
    byte[] in = "This is a test".getBytes();

    keyGen.initialize(elParams);

    KeyPair keyPair = keyGen.generateKeyPair();
    SecureRandom rand = new SecureRandom();

    checkKeySize(privateValueSize, keyPair);

    Cipher cipher = Cipher.getInstance("ElGamal", "BC");

    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

    if (cipher.getOutputSize(in.length) != (size / 8) * 2) {
      fail("getOutputSize wrong on encryption");
    }

    byte[] out = cipher.doFinal(in);

    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

    if (cipher.getOutputSize(out.length) != (size / 8) - 1) {
      fail("getOutputSize wrong on decryption");
    }

    //
    // No Padding - maximum length
    //
    byte[] modBytes = ((DHPublicKey) keyPair.getPublic()).getParams().getP().toByteArray();
    byte[] maxInput = new byte[modBytes.length - 1];

    maxInput[0] |= 0x7f;

    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

    out = cipher.doFinal(maxInput);

    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

    out = cipher.doFinal(out);

    if (!areEqual(out, maxInput)) {
      fail(
          "NoPadding test failed on decrypt expected "
              + new String(Hex.encode(maxInput))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    // encrypt/decrypt
    //

    Cipher c1 = Cipher.getInstance("ElGamal", "BC");
    Cipher c2 = Cipher.getInstance("ElGamal", "BC");

    c1.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

    byte[] out1 = c1.doFinal(in);

    c2.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

    byte[] out2 = c2.doFinal(out1);

    if (!areEqual(in, out2)) {
      fail(size + " encrypt test failed");
    }

    //
    // encrypt/decrypt with update
    //
    int outLen = c1.update(in, 0, 2, out1, 0);

    outLen += c1.doFinal(in, 2, in.length - 2, out1, outLen);

    outLen = c2.update(out1, 0, 2, out2, 0);

    outLen += c2.doFinal(out1, 2, out1.length - 2, out2, outLen);

    if (!areEqual(in, out2)) {
      fail(size + " encrypt with update test failed");
    }

    //
    // public key encoding test
    //
    byte[] pubEnc = keyPair.getPublic().getEncoded();
    KeyFactory keyFac = KeyFactory.getInstance("ElGamal", "BC");
    X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
    DHPublicKey pubKey = (DHPublicKey) keyFac.generatePublic(pubX509);
    DHParameterSpec spec = pubKey.getParams();

    if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP())) {
      fail(size + " bit public key encoding/decoding test failed on parameters");
    }

    if (!((DHPublicKey) keyPair.getPublic()).getY().equals(pubKey.getY())) {
      fail(size + " bit public key encoding/decoding test failed on y value");
    }

    //
    // public key serialisation test
    //
    pubKey = (DHPublicKey) serializeDeserialize(keyPair.getPublic());
    spec = pubKey.getParams();

    if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP())) {
      fail(size + " bit public key serialisation test failed on parameters");
    }

    if (!((DHPublicKey) keyPair.getPublic()).getY().equals(pubKey.getY())) {
      fail(size + " bit public key serialisation test failed on y value");
    }

    if (!keyPair.getPublic().equals(pubKey)) {
      fail("equals test failed");
    }

    if (keyPair.getPublic().hashCode() != pubKey.hashCode()) {
      fail("hashCode test failed");
    }

    //
    // private key encoding test
    //
    byte[] privEnc = keyPair.getPrivate().getEncoded();
    PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
    DHPrivateKey privKey = (DHPrivateKey) keyFac.generatePrivate(privPKCS8);

    spec = privKey.getParams();

    if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP())) {
      fail(size + " bit private key encoding/decoding test failed on parameters");
    }

    if (!((DHPrivateKey) keyPair.getPrivate()).getX().equals(privKey.getX())) {
      fail(size + " bit private key encoding/decoding test failed on y value");
    }

    //
    // private key serialisation test
    //
    privKey = (DHPrivateKey) serializeDeserialize(keyPair.getPrivate());
    spec = privKey.getParams();

    if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP())) {
      fail(size + " bit private key serialisation test failed on parameters");
    }

    if (!((DHPrivateKey) keyPair.getPrivate()).getX().equals(privKey.getX())) {
      fail(size + " bit private key serialisation test failed on y value");
    }

    if (!keyPair.getPrivate().equals(privKey)) {
      fail("equals test failed");
    }

    if (keyPair.getPrivate().hashCode() != privKey.hashCode()) {
      fail("hashCode test failed");
    }

    if (!(privKey instanceof PKCS12BagAttributeCarrier)) {
      fail("private key not implementing PKCS12 attribute carrier");
    }
  }
Ejemplo n.º 16
0
  public static Message decode(Session session, String text) {
    Logger logger = LoggerFactory.getLogger(KrakenMessageDecoder.class.getName());
    Charset utf8 = Charset.forName("utf-8");

    // remove potential control characters
    text = text.trim();
    if (text.length() == 0) return null;

    if (logger.isDebugEnabled())
      logger.debug(
          "kraken webconsole: debug websocket frame length {}, json [{}]", text.length(), text);

    if (text.equals("ping")) return null;

    // decrypt if msg is encrypted
    if (session.has("enc_key")) {
      try {
        JSONTokener tokenizer = new JSONTokener(new StringReader(text));
        JSONArray container = (JSONArray) tokenizer.nextValue();
        JSONObject header = container.getJSONObject(0);
        JSONObject body = container.getJSONObject(1);

        if (header.has("iv") && body.has("data")) {
          String data = body.getString("data");

          byte[] iv =
              ByteUtil.asArray(
                  Base64.decode(ChannelBuffers.wrappedBuffer(header.getString("iv").getBytes())));
          byte[] buf =
              ByteUtil.asArray(Base64.decode(ChannelBuffers.wrappedBuffer(data.getBytes())));
          byte[] key = ByteUtil.asByteArray(UUID.fromString(session.getString("enc_key")));
          SecretKeySpec secret = new SecretKeySpec(key, "AES");

          Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
          cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
          byte[] plain = new byte[cipher.getOutputSize(buf.length)];
          int plainLength = cipher.update(buf, 0, buf.length, plain, 0);
          plainLength += cipher.doFinal(plain, plainLength);

          text = new String(plain, 0, plainLength, utf8);
          logger.trace("kraken webconsole: decrypted msg [{}]", text);
        }
      } catch (Exception e) {
        logger.error("kraken webconsole: cannot decode encrypted msg [" + text + "]", e);
      }
    }

    try {
      JSONTokener tokenizer = new JSONTokener(new StringReader(text));
      JSONArray container = (JSONArray) tokenizer.nextValue();
      JSONObject header = container.getJSONObject(0);
      JSONObject body = container.getJSONObject(1);

      Message msg = new Message();

      msg.setGuid(header.getString("guid").trim());
      msg.setType(Message.Type.valueOf(header.getString("type").trim()));
      msg.setSource(header.getString("source"));
      msg.setTarget(header.getString("target"));
      msg.setMethod(header.getString("method").trim());
      msg.setParameters(parse(body));

      return msg;
    } catch (JSONException e) {
      logger.error("kraken webconsole: invalid json => " + text, e);
    }
    return null;
  }
Ejemplo n.º 17
0
  private void testDefault(int privateValueSize, BigInteger g, BigInteger p) throws Exception {
    DHParameterSpec elParams = new DHParameterSpec(p, g, privateValueSize);
    int size = p.bitLength();

    new BouncyCastleProvider().setParameter(ConfigurableProvider.DH_DEFAULT_PARAMS, elParams);

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ElGamal", "BC");
    byte[] in = "This is a test".getBytes();

    keyGen.initialize(p.bitLength());

    KeyPair keyPair = keyGen.generateKeyPair();

    new BouncyCastleProvider().setParameter(ConfigurableProvider.DH_DEFAULT_PARAMS, elParams);

    SecureRandom rand = new SecureRandom();

    checkKeySize(privateValueSize, keyPair);

    Cipher cipher = Cipher.getInstance("ElGamal", "BC");

    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

    if (cipher.getOutputSize(in.length) != (size / 8) * 2) {
      fail("getOutputSize wrong on encryption");
    }

    byte[] out = cipher.doFinal(in);

    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

    if (cipher.getOutputSize(out.length) != (size / 8) - 1) {
      fail("getOutputSize wrong on decryption");
    }

    //
    // No Padding - maximum length
    //
    byte[] modBytes = ((DHPublicKey) keyPair.getPublic()).getParams().getP().toByteArray();
    byte[] maxInput = new byte[modBytes.length - 1];

    maxInput[0] |= 0x7f;

    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

    out = cipher.doFinal(maxInput);

    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

    out = cipher.doFinal(out);

    if (!areEqual(out, maxInput)) {
      fail(
          "NoPadding test failed on decrypt expected "
              + new String(Hex.encode(maxInput))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    // encrypt/decrypt
    //

    Cipher c1 = Cipher.getInstance("ElGamal", "BC");
    Cipher c2 = Cipher.getInstance("ElGamal", "BC");

    c1.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

    byte[] out1 = c1.doFinal(in);

    c2.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

    byte[] out2 = c2.doFinal(out1);

    if (!areEqual(in, out2)) {
      fail(size + " encrypt test failed");
    }

    //
    // encrypt/decrypt with update
    //
    int outLen = c1.update(in, 0, 2, out1, 0);

    outLen += c1.doFinal(in, 2, in.length - 2, out1, outLen);

    outLen = c2.update(out1, 0, 2, out2, 0);

    outLen += c2.doFinal(out1, 2, out1.length - 2, out2, outLen);

    if (!areEqual(in, out2)) {
      fail(size + " encrypt with update test failed");
    }

    //
    // public key encoding test
    //
    byte[] pubEnc = keyPair.getPublic().getEncoded();
    KeyFactory keyFac = KeyFactory.getInstance("ElGamal", "BC");
    X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
    DHPublicKey pubKey = (DHPublicKey) keyFac.generatePublic(pubX509);
    DHParameterSpec spec = pubKey.getParams();

    if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP())) {
      fail(size + " bit public key encoding/decoding test failed on parameters");
    }

    if (!((DHPublicKey) keyPair.getPublic()).getY().equals(pubKey.getY())) {
      fail(size + " bit public key encoding/decoding test failed on y value");
    }

    //
    // public key serialisation test
    //
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ObjectOutputStream oOut = new ObjectOutputStream(bOut);

    oOut.writeObject(keyPair.getPublic());

    ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
    ObjectInputStream oIn = new ObjectInputStream(bIn);

    pubKey = (DHPublicKey) oIn.readObject();
    spec = pubKey.getParams();

    if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP())) {
      fail(size + " bit public key serialisation test failed on parameters");
    }

    if (!((DHPublicKey) keyPair.getPublic()).getY().equals(pubKey.getY())) {
      fail(size + " bit public key serialisation test failed on y value");
    }

    //
    // private key encoding test
    //
    byte[] privEnc = keyPair.getPrivate().getEncoded();
    PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
    DHPrivateKey privKey = (DHPrivateKey) keyFac.generatePrivate(privPKCS8);

    spec = privKey.getParams();

    if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP())) {
      fail(size + " bit private key encoding/decoding test failed on parameters");
    }

    if (!((DHPrivateKey) keyPair.getPrivate()).getX().equals(privKey.getX())) {
      fail(size + " bit private key encoding/decoding test failed on y value");
    }

    //
    // private key serialisation test
    //
    bOut = new ByteArrayOutputStream();
    oOut = new ObjectOutputStream(bOut);

    oOut.writeObject(keyPair.getPrivate());

    bIn = new ByteArrayInputStream(bOut.toByteArray());
    oIn = new ObjectInputStream(bIn);

    privKey = (DHPrivateKey) oIn.readObject();
    spec = privKey.getParams();

    if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP())) {
      fail(size + " bit private key serialisation test failed on parameters");
    }

    if (!((DHPrivateKey) keyPair.getPrivate()).getX().equals(privKey.getX())) {
      fail(size + " bit private key serialisation test failed on y value");
    }
  }