コード例 #1
0
ファイル: RSAUtils.java プロジェクト: myicewater/book-wx
 /**
  * 私钥加密
  *
  * @param data 源数据
  * @param privateKey 私钥(BASE64编码)
  * @return
  * @throws Exception
  */
 public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
   byte[] keyBytes = Base64.decode(privateKey);
   PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
   KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
   Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
   Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
   cipher.init(Cipher.ENCRYPT_MODE, privateK);
   int inputLen = data.length;
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   int offSet = 0;
   byte[] cache;
   int i = 0;
   // 对数据分段加密
   while (inputLen - offSet > 0) {
     if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
       cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
     } else {
       cache = cipher.doFinal(data, offSet, inputLen - offSet);
     }
     out.write(cache, 0, cache.length);
     i++;
     offSet = i * MAX_ENCRYPT_BLOCK;
   }
   byte[] encryptedData = out.toByteArray();
   out.close();
   return encryptedData;
 }
コード例 #2
0
  private void testAlgorithm(
      String name, byte[] keyBytes, byte[] iv, byte[] plainText, byte[] cipherText)
      throws Exception {
    SecretKey key = new SecretKeySpec(keyBytes, name);
    Cipher in = Cipher.getInstance(name, "BC");
    Cipher out = Cipher.getInstance(name, "BC");

    if (iv != null) {
      in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
      out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
    } else {
      in.init(Cipher.ENCRYPT_MODE, key);
      out.init(Cipher.DECRYPT_MODE, key);
    }

    byte[] enc = in.doFinal(plainText);
    if (!areEqual(enc, cipherText)) {
      fail(name + ": cipher text doesn't match");
    }

    byte[] dec = out.doFinal(enc);

    if (!areEqual(dec, plainText)) {
      fail(name + ": plain text doesn't match");
    }
  }
コード例 #3
0
  public byte[] new_decrypt_cn(E_CODE paramE_CODE, byte[] paramArrayOfByte)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
          InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    byte[] localObject = null;

    if (paramE_CODE == E_CODE.RSA) {
      if (rsa_key.length() > 2) {
        Cipher localCipher;
        byte[] arrayOfByte = new byte[0];
        //		    PublicKey localPublicKey = KeyFactory.getInstance("RSA").generatePublic(new
        // X509EncodedKeySpec(Base64.decodeBase64(rsa_key)));
        PublicKey localPublicKey =
            KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(Base64.decode(rsa_key, Base64.DEFAULT)));
        System.out.println("key  length-" + (Base64.decode(rsa_key, Base64.DEFAULT)).length);
        System.out.println("data length-" + paramArrayOfByte.length);
        localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        localCipher.init(Cipher.DECRYPT_MODE, localPublicKey);
        //		    localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);

        arrayOfByte = localCipher.doFinal(paramArrayOfByte);
        //		    int oldLength;
        //		    for (int i = 0; i < paramArrayOfByte.length; i += 8) {
        //		        byte[] temp = localCipher.doFinal(paramArrayOfByte, i, i + 8);
        //		        oldLength = arrayOfByte.length;
        //		        arrayOfByte  = Arrays.copyOf(arrayOfByte, temp.length+arrayOfByte.length);
        //		        System.arraycopy(temp, 0, arrayOfByte, oldLength, temp.length);
        //		    }

        //		    arrayOfByte = paramArrayOfByte;

        return arrayOfByte;
      }
    } else if (paramE_CODE == E_CODE.RSA_EP) {
      if (rsa_ep_key.length() >= 2) {
        //        PrivateKey localPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(new
        // PKCS8EncodedKeySpec(Base64.decodeBase64(rsa_ep_key)));
        PrivateKey localPrivateKey =
            KeyFactory.getInstance("RSA")
                .generatePrivate(
                    new PKCS8EncodedKeySpec(Base64.decode(rsa_ep_key, Base64.DEFAULT)));
        Cipher localCipher2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        localCipher2.init(2, localPrivateKey);
        localObject = localCipher2.doFinal(paramArrayOfByte);
      }
    } else if (paramE_CODE == E_CODE.AES) {
      //      SecretKeySpec localSecretKeySpec = new
      // SecretKeySpec(Base64.decodeBase64(aes_key.getBytes()), "AES");
      //      byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte);
      SecretKeySpec localSecretKeySpec =
          new SecretKeySpec(Base64.decode(aes_key.getBytes(), Base64.DEFAULT), "AES");
      byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT);
      Cipher localCipher1 = Cipher.getInstance("AES/ECB/PKCS5Padding");
      localCipher1.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
      byte[] arrayOfByte2 = localCipher1.doFinal(arrayOfByte1);
      localObject = arrayOfByte2;
    }

    return localObject;
  }
コード例 #4
0
  private void validateKeys(PublicKey pubKey, PrivateKey privKey) {

    if (pubKey.getAlgorithm() != privKey.getAlgorithm())
      throw new IllegalArgumentException("Public and private key have different algorithms");

    // No encryption for DSA
    if (pubKey.getAlgorithm() != "RSA") return;

    try {

      String data = "ENCRYPT_DATA";
      SecureRandom random = new SecureRandom();
      Cipher cipher = Cipher.getInstance(pubKey.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, privKey, random);
      byte[] encryptedData = cipher.doFinal(data.getBytes());

      cipher.init(Cipher.DECRYPT_MODE, pubKey, random);
      String decreptedData = new String(cipher.doFinal(encryptedData));
      if (!decreptedData.equals(data)) throw new IllegalArgumentException("Bad public-private key");

    } catch (BadPaddingException e) {
      throw new IllegalArgumentException("Bad public-private key", e);
    } catch (IllegalBlockSizeException e) {
      throw new IllegalArgumentException("Bad public-private key", e);
    } catch (NoSuchPaddingException e) {
      throw new IllegalArgumentException("Bad public-private key", e);
    } catch (InvalidKeyException e) {
      throw new IllegalArgumentException("Invalid public-private key", e);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalArgumentException("Invalid algorithm for public-private key", e);
    }
  }
コード例 #5
0
  public byte[] encrypt(byte[] data)
      throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IOException,
          InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException,
          InvalidAlgorithmParameterException {
    Cipher cipher = getCipherInstance();

    if (JCryptoHelper.isNecessaryIvBytes(this.jcrypto.getAlgorithm())) {
      IvParameterSpec ivParameterSpec = new IvParameterSpec(JCryptoHelper.DEFAULT_IV_BYTES);
      cipher.init(
          Cipher.ENCRYPT_MODE,
          generateKey(
              JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
              this.jcrypto.getAlgorithm(),
              this.jcrypto.getKeyBytes()),
          ivParameterSpec);
    } else {
      cipher.init(
          Cipher.ENCRYPT_MODE,
          generateKey(
              JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
              this.jcrypto.getAlgorithm(),
              this.jcrypto.getKeyBytes()));
    }
    if (jcrypto.isApplyBase64()) {
      // sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
      // return encoder.encode(cipher.doFinal(data)).getBytes();
      return Base64.encodeBase64(cipher.doFinal(data));

    } else {
      return cipher.doFinal(data);
    }
  }
コード例 #6
0
ファイル: DESTest.java プロジェクト: popocai/studyhub
  private static void bcDES() throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    // Key convert
    DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
    SecretKeyFactory factory = SecretKeyFactory.getInstance("DES", "BC");
    SecretKey desKey = factory.generateSecret(desKeySpec);

    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, desKey);

    System.out.println("BC" + cipher.getProvider());

    byte[] result = cipher.doFinal("ABC".getBytes());
    String hexResult = Hex.encodeHexString(result);
    System.out.println(hexResult);

    cipher.init(Cipher.DECRYPT_MODE, desKey);
    result =
        cipher.doFinal(
            Hex.decodeHex(hexResult.toCharArray())
            // result
            );
    System.out.println(new String(result));
  }
コード例 #7
0
ファイル: GOST28147Test.java プロジェクト: XShandow/bc-java
  private void oidTest() {
    String[] oids = {
      CryptoProObjectIdentifiers.gostR28147_gcfb.getId(),
    };

    String[] names = {"GOST28147/GCFB/NoPadding"};

    try {

      byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
      IvParameterSpec ivSpec = new IvParameterSpec(new byte[8]);

      for (int i = 0; i != oids.length; i++) {
        Cipher c1 = Cipher.getInstance(oids[i], "BC");
        Cipher c2 = Cipher.getInstance(names[i], "BC");
        KeyGenerator kg = KeyGenerator.getInstance(oids[i], "BC");

        SecretKey k = kg.generateKey();

        c1.init(Cipher.ENCRYPT_MODE, k, ivSpec);
        c2.init(Cipher.DECRYPT_MODE, k, ivSpec);

        byte[] result = c2.doFinal(c1.doFinal(data));

        if (!areEqual(data, result)) {
          fail("failed OID test");
        }
      }
    } catch (Exception ex) {
      fail("failed exception " + ex.toString(), ex);
    }
  }
コード例 #8
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");
    }
  }
コード例 #9
0
ファイル: TestGCM.java プロジェクト: kexianda/misc
  private static byte[] gcmEncrypt(byte[] key, byte[] plainText, byte[] aad, byte[] iv) {
    byte[] cipherText = new byte[plainText.length + 16];
    try {

      SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
      GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
      Cipher cipher = Cipher.getInstance(ALGORITHM + "/" + MODE + "/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec);

      if (aad != null && aad.length != 0) {
        cipher.updateAAD(aad);
      }

      // if has more than one blocks, test cipher.update
      if (plainText.length > 16) {
        cipher.update(plainText, 0, 16, cipherText, 0);
        cipher.doFinal(plainText, 16, plainText.length - 16, cipherText, 16);
      } else {
        // doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
        cipher.doFinal(plainText, 0, plainText.length, cipherText, 0);
      }

    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return cipherText;
  }
コード例 #10
0
 void run() throws Exception {
   Cipher cipher = Cipher.getInstance("RC2/ECB/NOPADDING", "SunJCE");
   SecretKey keySpec = new SecretKeySpec(key, "RC2");
   RC2ParameterSpec rc2Spec = new RC2ParameterSpec(effectiveKeySize);
   cipher.init(Cipher.ENCRYPT_MODE, keySpec, rc2Spec);
   byte[] enc = cipher.doFinal(plaintext);
   if (Arrays.equals(ciphertext, enc) == false) {
     System.out.println("RC2AlgorithmParameters Cipher test " + "encryption failed:");
     System.out.println("plaintext:  " + RC2AlgorithmParameters.toString(plaintext));
     System.out.println("ciphertext: " + RC2AlgorithmParameters.toString(ciphertext));
     System.out.println("encrypted:  " + RC2AlgorithmParameters.toString(enc));
     System.out.println("key:        " + RC2AlgorithmParameters.toString(key));
     System.out.println("effective key length:        " + effectiveKeySize);
     throw new Exception("RC2AlgorithmParameters Cipher test " + "encryption failed");
   }
   enc = cipher.doFinal(plaintext);
   if (Arrays.equals(ciphertext, enc) == false) {
     throw new Exception("Re-encryption test failed");
   }
   cipher.init(Cipher.DECRYPT_MODE, keySpec, rc2Spec);
   byte[] dec = cipher.doFinal(ciphertext);
   if (Arrays.equals(plaintext, dec) == false) {
     System.out.println("RC2AlgorithmParameters Cipher test " + "decryption failed:");
     System.out.println("plaintext:  " + RC2AlgorithmParameters.toString(plaintext));
     System.out.println("ciphertext: " + RC2AlgorithmParameters.toString(ciphertext));
     System.out.println("decrypted:  " + RC2AlgorithmParameters.toString(dec));
     System.out.println("key:        " + RC2AlgorithmParameters.toString(key));
     System.out.println("effective key length:        " + effectiveKeySize);
     throw new Exception("RC2AlgorithmParameters Cipher test " + "decryption failed");
   }
   System.out.println("passed");
 }
コード例 #11
0
  public static void main(String[] args) throws Exception {
    byte[] input = new byte[] {(byte) 0xbe, (byte) 0xef};
    Cipher cipher = Cipher.getInstance("ElGamal/None/NoPadding", "BC");

    SecureRandom random = Utils.createFixedRandom();

    // create the keys
    KeyPairGenerator generator = KeyPairGenerator.getInstance("ElGamal", "BC");

    generator.initialize(256, random);

    KeyPair pair = generator.generateKeyPair();
    Key pubKey = pair.getPublic();
    Key privKey = pair.getPrivate();

    System.out.println("input : " + Utils.toHex(input));

    // encryption step

    cipher.init(Cipher.ENCRYPT_MODE, pubKey, random);

    byte[] cipherText = cipher.doFinal(input);

    System.out.println("cipher: " + Utils.toHex(cipherText));

    // decryption step

    cipher.init(Cipher.DECRYPT_MODE, privKey);

    byte[] plainText = cipher.doFinal(cipherText);

    System.out.println("plain : " + Utils.toHex(plainText));
  }
コード例 #12
0
ファイル: CryptoUtils.java プロジェクト: jimpo/arpeggio
  public static Message encrypt(PublicKey pubKey, byte[] input) throws CryptoException {
    Message message = new Message();
    message.pubKey = pubKey.getEncoded();

    KeyGenerator keyGen;
    try {
      keyGen = KeyGenerator.getInstance("AES");
    } catch (NoSuchAlgorithmException e) {
      throw new CryptoException(e);
    }
    keyGen.init(128);
    SecretKey secretKey = keyGen.generateKey();

    try {
      Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey);
      message.sessionKey = rsaCipher.doFinal(secretKey.getEncoded());

      Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
      AlgorithmParameters params = aesCipher.getParameters();
      message.iv = params.getParameterSpec(IvParameterSpec.class).getIV();
      message.ciphertext = aesCipher.doFinal(input);
    } catch (NoSuchAlgorithmException
        | NoSuchPaddingException
        | InvalidKeyException
        | IllegalBlockSizeException
        | BadPaddingException
        | InvalidParameterSpecException e) {
      throw new CryptoException(e);
    }

    return message;
  }
コード例 #13
0
ファイル: SecurityUtil.java プロジェクト: RalphC/upmp
  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;
    }
  }
コード例 #14
0
ファイル: RSAUtils.java プロジェクト: yiguang-team/payment
 /**
  * 公钥解密
  *
  * @param encryptedData 已加密数据
  * @param publicKey 公钥(BASE64编码)
  * @return
  * @throws Exception
  */
 public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
   byte[] keyBytes = Base64Utils.decode(publicKey);
   X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
   KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
   Key publicK = keyFactory.generatePublic(x509KeySpec);
   Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
   cipher.init(Cipher.DECRYPT_MODE, publicK);
   int inputLen = encryptedData.length;
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   int offSet = 0;
   byte[] cache;
   int i = 0;
   // 对数据分段解密
   while (inputLen - offSet > 0) {
     if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
       cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
     } else {
       cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
     }
     out.write(cache, 0, cache.length);
     i++;
     offSet = i * MAX_DECRYPT_BLOCK;
   }
   byte[] decryptedData = out.toByteArray();
   out.close();
   return decryptedData;
 }
コード例 #15
0
ファイル: CryptoUtils.java プロジェクト: jimpo/arpeggio
  public static byte[] decrypt(PrivateKey privKey, Message message) throws CryptoException {
    try {
      Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      rsaCipher.init(Cipher.DECRYPT_MODE, privKey);
      byte[] secretKeyBytes = rsaCipher.doFinal(message.sessionKey);

      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES");
      KeySpec ks = new SecretKeySpec(secretKeyBytes, "AES");
      SecretKey secretKey = keyFactory.generateSecret(ks);

      Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      aesCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(message.iv));
      byte[] messageBytes = aesCipher.doFinal(message.ciphertext);

      return messageBytes;
    } catch (NoSuchAlgorithmException
        | NoSuchPaddingException
        | InvalidKeyException
        | IllegalBlockSizeException
        | BadPaddingException
        | InvalidKeySpecException
        | InvalidAlgorithmParameterException e) {
      throw new CryptoException(e);
    }
  }
コード例 #16
0
ファイル: ECIESTest.java プロジェクト: XShandow/bc-java
  public void doTest(String testname, KeyPairGenerator g, String cipher, IESParameterSpec p)
      throws Exception {

    byte[] message = Hex.decode("0102030405060708090a0b0c0d0e0f10111213141516");
    byte[] out1, out2;

    // Generate static key pair
    KeyPair KeyPair = g.generateKeyPair();
    ECPublicKey Pub = (ECPublicKey) KeyPair.getPublic();
    ECPrivateKey Priv = (ECPrivateKey) KeyPair.getPrivate();

    Cipher c1 = Cipher.getInstance(cipher);
    Cipher c2 = Cipher.getInstance(cipher);

    // Testing with null parameters and DHAES mode off
    c1.init(Cipher.ENCRYPT_MODE, Pub, new SecureRandom());
    c2.init(Cipher.DECRYPT_MODE, Priv, new SecureRandom());
    out1 = c1.doFinal(message, 0, message.length);
    out2 = c2.doFinal(out1, 0, out1.length);
    if (!areEqual(out2, message))
      fail(testname + " test failed with null parameters, DHAES mode false.");

    // Testing with given parameters and DHAES mode off
    c1.init(Cipher.ENCRYPT_MODE, Pub, p, new SecureRandom());
    c2.init(Cipher.DECRYPT_MODE, Priv, p, new SecureRandom());
    out1 = c1.doFinal(message, 0, message.length);
    out2 = c2.doFinal(out1, 0, out1.length);
    if (!areEqual(out2, message))
      fail(testname + " test failed with non-null parameters, DHAES mode false.");

    // TODO: DHAES mode is not currently implemented, perhaps it shouldn't be...
    //        c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC");
    //        c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC");
    //
    //        // Testing with null parameters and DHAES mode on
    //        c1.init(Cipher.ENCRYPT_MODE, Pub, new SecureRandom());
    //        c2.init(Cipher.DECRYPT_MODE, Priv, new SecureRandom());
    //
    //        out1 = c1.doFinal(message, 0, message.length);
    //        out2 = c2.doFinal(out1, 0, out1.length);
    //        if (!areEqual(out2, message))
    //            fail(testname + " test failed with null parameters, DHAES mode true.");
    //
    //        c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding");
    //        c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding");
    //
    //        // Testing with given parameters and DHAES mode on
    //        c1.init(Cipher.ENCRYPT_MODE, Pub, p, new SecureRandom());
    //        c2.init(Cipher.DECRYPT_MODE, Priv, p, new SecureRandom());
    //
    //        out1 = c1.doFinal(message, 0, message.length);
    //        out2 = c2.doFinal(out1, 0, out1.length);
    //        if (!areEqual(out2, message))
    //            fail(testname + " test failed with non-null parameters, DHAES mode true.");

  }
コード例 #17
0
ファイル: AESTest.java プロジェクト: silvajs/dota-web
  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);
    }
  }
コード例 #18
0
  public boolean shareAESkey() {
    try {
      Envelope message = null, e = null;

      // Generate AES key
      KeyGenerator keyGen = KeyGenerator.getInstance("AES");
      AESkey = keyGen.generateKey();
      keyGen = KeyGenerator.getInstance("HmacSHA1");
      HMACkey = keyGen.generateKey();
      byte[] keyBytes = AESkey.getEncoded();
      byte[] hashBytes = HMACkey.getEncoded();
      System.out.println("AES key generated");
      System.out.println("HMAC key generated");
      System.out.println("Begin Encryption...");
      // Encrypt message  w/ provided public key
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

      cipher.init(Cipher.ENCRYPT_MODE, pubKey);
      byte[] cipherBytes = cipher.doFinal(keyBytes);
      byte[] cipherBytes1 = cipher.doFinal(hashBytes);
      System.out.println("Encryption Complete");

      message = new Envelope("SKEY");
      message.addObject(cipherBytes); // Add AESkey to message
      message.addObject(cipherBytes1);
      message.addObject(nonce);
      nonce++;

      byte[] messageBytes = Envelope.toByteArray(message);

      output.writeObject(messageBytes);

      byte[] inCipherBytes = (byte[]) input.readObject();

      // Decrypt response
      cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE, AESkey);
      byte[] responseBytes = cipher.doFinal(inCipherBytes);

      Envelope response = Envelope.getEnvelopefromBytes(responseBytes);

      // If server indicates success, return the member list
      if (response.getMessage().equals("OK")
          && (Integer) response.getObjContents().get(0) == nonce) {
        return true;
      } else {
        return false;
      }
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
      e.printStackTrace(System.err);
      return false;
    }
  }
コード例 #19
0
  public static void main(String[] args) throws Exception {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    // get user inputted key
    byte[] userkey = null;
    do {
      System.out.println("Please enter a 8 character string to generate a Secret Key");
      userkey = (in.readLine()).getBytes();
    } while (userkey.length != 8);

    // create Key Generator instance and generate a secret key
    KeyGenerator kgen = KeyGenerator.getInstance("DES");
    SecretKey skey = kgen.generateKey();

    byte[] key = userkey;
    // Create a Secret Key based on characters entered by the user
    SecretKeySpec skeyspec = new SecretKeySpec(key, "DES");

    // Create a cipher to encrypt with
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeyspec);

    // Get message
    System.out.println("Please enter a string to encrypt");
    byte[] userstring = null;
    userstring = (in.readLine()).getBytes();

    // Encrypt message with cipher
    byte[] encrypted = cipher.doFinal(userstring);
    String enc_string = new String(encrypted);
    System.out.println("The String is encrypted as " + enc_string);

    byte[] userdecrypt = null;
    byte[] decrypted = null;

    // Get user decrypt key
    do {
      System.out.println("Please enter the 8 character key to decrypt the message");
      userdecrypt = (in.readLine()).getBytes();
    } while (userdecrypt.length != 8);

    // Reinitialize Secret Key and Cipher
    key = userdecrypt;
    SecretKeySpec decryptkey = new SecretKeySpec(key, "DES");
    cipher.init(Cipher.DECRYPT_MODE, decryptkey);

    // Decrypt message
    decrypted = cipher.doFinal(encrypted);

    if ((new String(decrypted)).equals(new String(userstring)))
      System.out.println("\nMessage decrypted as: " + (new String(decrypted)));
    else System.out.println("\nMessage was not decrypted");
  }
コード例 #20
0
ファイル: RSATest.java プロジェクト: goldcoin/java-experiment
  private void oaepCompatibilityTest(String digest, PrivateKey privKey, PublicKey pubKey)
      throws Exception {
    if (Security.getProvider("SunJCE") == null || Security.getProvider("SunRsaSign") == null) {
      return;
    }

    KeyFactory fact = KeyFactory.getInstance("RSA", "SunRsaSign");
    PrivateKey priv2048Key = fact.generatePrivate(priv2048KeySpec);
    PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec);

    byte[] data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};

    Cipher sCipher;
    try {
      sCipher = Cipher.getInstance("RSA/ECB/OAEPWith" + digest + "AndMGF1Padding", "SunJCE");
    } catch (NoSuchAlgorithmException e) {
      return;
    } catch (NoSuchPaddingException e) {
      return;
    }

    sCipher.init(Cipher.ENCRYPT_MODE, pub2048Key);

    byte[] enctext = sCipher.doFinal(data);

    Cipher bcCipher = Cipher.getInstance("RSA/ECB/OAEPWith" + digest + "AndMGF1Padding", "BC");

    bcCipher.init(
        Cipher.DECRYPT_MODE,
        privKey,
        new OAEPParameterSpec(digest, "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));

    byte[] plaintext = bcCipher.doFinal(enctext);

    if (!Arrays.areEqual(plaintext, data)) {
      fail("data did not decrypt first time");
    }

    bcCipher.init(
        Cipher.ENCRYPT_MODE,
        pubKey,
        new OAEPParameterSpec(digest, "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));

    enctext = bcCipher.doFinal(data);

    sCipher.init(Cipher.DECRYPT_MODE, priv2048Key);

    plaintext = sCipher.doFinal(enctext);

    if (!Arrays.areEqual(plaintext, data)) {
      fail("data did not decrypt second time");
    }
  }
コード例 #21
0
ファイル: TestSAT.java プロジェクト: jsigle/elexis-base
  public void testModule() throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // Add

    // Create the secret/symmetric key
    KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");

    // Create the cipher for encrypting
    Cipher cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

    // Encrypt the data
    byte[] encrypted = cipher.doFinal(plain);

    // Save the encrypted data
    FileOutputStream fos = new FileOutputStream(datafile);
    fos.write(encrypted);
    fos.close();

    // Save the cipher settings
    byte[] encodedKeySpec = skeySpec.getEncoded();
    FileOutputStream eksos = new FileOutputStream(keyfile);
    eksos.write(encodedKeySpec);
    eksos.close();

    // Read the encrypted data
    FileInputStream fis = new FileInputStream(datafile);
    byte[] temp = new byte[8192];
    int bytesRead = fis.read(temp);
    byte[] data = new byte[bytesRead];
    System.arraycopy(temp, 0, data, 0, bytesRead);

    // Read the cipher settings
    FileInputStream eksis = new FileInputStream(keyfile);
    bytesRead = eksis.read(temp);
    encodedKeySpec = new byte[bytesRead];
    System.arraycopy(temp, 0, encodedKeySpec, 0, bytesRead);

    // Recreate the secret/symmetric key
    skeySpec = new SecretKeySpec(encodedKeySpec, "Blowfish");

    // Create the cipher for encrypting
    cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);

    // Decrypt the data
    byte[] decrypted = cipher.doFinal(data);

    assertTrue(Arrays.equals(decrypted, plain));
  }
コード例 #22
0
  public static SecretKey getSecret(EncryptionResponse resp, EncryptionRequest request)
      throws GeneralSecurityException {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());
    byte[] decrypted = cipher.doFinal(resp.getVerifyToken());

    if (!Arrays.equals(request.getVerifyToken(), decrypted)) {
      throw new IllegalStateException("Key pairs do not match!");
    }

    cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());
    return new SecretKeySpec(cipher.doFinal(resp.getSharedSecret()), "AES");
  }
コード例 #23
0
  private byte[] blockCipher(byte[] bytes, int mode, Cipher cipher)
      throws IllegalBlockSizeException, BadPaddingException {
    // string initialize 2 buffers.
    // scrambled will hold intermediate results
    byte[] scrambled = new byte[0];

    // toReturn will hold the total result
    byte[] toReturn = new byte[0];
    // if we encrypt we use 100 byte long blocks. Decryption requires 128
    // byte long blocks (because of RSA)
    int length = (mode == Cipher.ENCRYPT_MODE) ? 100 : 128;

    // another buffer. this one will hold the bytes that have to be modified
    // in this step
    byte[] buffer = new byte[length];

    for (int i = 0; i < bytes.length; i++) {

      // if we filled our buffer array we have our block ready for de- or
      // encryption
      if ((i > 0) && (i % length == 0)) {
        // execute the operation
        scrambled = cipher.doFinal(buffer);
        // add the result to our total result.
        toReturn = append(toReturn, scrambled);
        // here we calculate the length of the next buffer required
        int newlength = length;

        // if newlength would be longer than remaining bytes in the
        // bytes array we shorten it.
        if (i + length > bytes.length) {
          newlength = bytes.length - i;
        }
        // clean the buffer array
        buffer = new byte[newlength];
      }
      // copy byte into our buffer.
      buffer[i % length] = bytes[i];
    }

    // this step is needed if we had a trailing buffer. should only happen
    // when encrypting.
    // example: we encrypt 110 bytes. 100 bytes per run means we "forgot"
    // the last 10 bytes. they are in the buffer array
    scrambled = cipher.doFinal(buffer);

    // final step before we can return the modified data.
    toReturn = append(toReturn, scrambled);

    return toReturn;
  }
コード例 #24
0
ファイル: AEADTest.java プロジェクト: abhinaypandey/bc-java
  private void testGCMGeneric(byte[] K, byte[] N, byte[] A, byte[] P, byte[] C)
      throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
          IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException,
          NoSuchProviderException, IOException, InvalidParameterSpecException {
    Cipher eax = Cipher.getInstance("AES/GCM/NoPadding", "BC");
    SecretKeySpec key = new SecretKeySpec(K, "AES");

    // GCMParameterSpec mapped to AEADParameters and overrides default MAC
    // size
    GCMParameterSpec spec = new GCMParameterSpec(128, N);
    eax.init(Cipher.ENCRYPT_MODE, key, spec);

    eax.updateAAD(A);
    byte[] c = eax.doFinal(P);

    if (!areEqual(C, c)) {
      fail("JCE encrypt with additional data and GCMParameterSpec failed.");
    }

    eax = Cipher.getInstance("GCM", "BC");
    eax.init(Cipher.DECRYPT_MODE, key, spec);
    eax.updateAAD(A);
    byte[] p = eax.doFinal(C);

    if (!areEqual(P, p)) {
      fail("JCE decrypt with additional data and GCMParameterSpec failed.");
    }

    AlgorithmParameters algParams = eax.getParameters();

    byte[] encParams = algParams.getEncoded();

    GCMParameters gcmParameters = GCMParameters.getInstance(encParams);

    if (!Arrays.areEqual(spec.getIV(), gcmParameters.getNonce())
        || spec.getTLen() != gcmParameters.getIcvLen()) {
      fail("parameters mismatch");
    }

    GCMParameterSpec gcmSpec = algParams.getParameterSpec(GCMParameterSpec.class);

    if (!Arrays.areEqual(gcmSpec.getIV(), gcmParameters.getNonce())
        || gcmSpec.getTLen() != gcmParameters.getIcvLen() * 8) {
      fail("spec parameters mismatch");
    }

    if (!Arrays.areEqual(eax.getIV(), gcmParameters.getNonce())) {
      fail("iv mismatch");
    }
  }
コード例 #25
0
  @Override
  public void requestPurchase(String sku) {
    try {
      SecureRandom sr;
      sr = SecureRandom.getInstance("SHA1PRNG");
      String uniqueId = Long.toHexString(sr.nextLong());

      JSONObject purchaseRequest = new JSONObject();
      purchaseRequest.put("uuid", uniqueId);
      purchaseRequest.put("identifier", sku);
      purchaseRequest.put("testing", TESTING);

      String purchaseRequestJson = purchaseRequest.toString();

      byte[] keyBytes = new byte[16];
      sr.nextBytes(keyBytes);
      SecretKey key = new SecretKeySpec(keyBytes, "AES");

      byte[] ivBytes = new byte[16];
      sr.nextBytes(ivBytes);
      IvParameterSpec iv = new IvParameterSpec(ivBytes);

      Cipher cipher;
      cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
      cipher.init(Cipher.ENCRYPT_MODE, key, iv);
      byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

      cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
      cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
      byte[] encryptedKey = cipher.doFinal(keyBytes);

      Purchasable purchasable =
          new Purchasable(
              sku,
              Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
              Base64.encodeToString(ivBytes, Base64.NO_WRAP),
              Base64.encodeToString(payload, Base64.NO_WRAP));

      //            synchronized (mOutstandingPurchaseRequests) {
      //                mOutstandingPurchaseRequests.put(uniqueId, product);
      //            }

      OuyaFacade.getInstance().requestPurchase(purchasable, this);

    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
コード例 #26
0
  public static byte[] encryptbytes(
      byte[] bytefile, SecretKey secretKey, byte[] nonceBuffer, int offset) {

    byte[] byteCipherText = null;
    try {
      final byte[] plaintext = bytefile;
      final byte[] nonce = nonceBuffer;
      final byte[] ciphertext = new byte[plaintext.length];

      Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
      final int skip = offset % BLOCK_SIZE;
      final IvParameterSpec nonceIV =
          calculateIVForOffset(
              generateIVFromNonce(nonce, 0, NONCE_SIZE, cipher.getBlockSize()), offset - skip);
      cipher.init(Cipher.ENCRYPT_MODE, secretKey, nonceIV);
      final byte[] skipBuffer = new byte[skip];
      cipher.update(skipBuffer, 0, skip, skipBuffer);
      cipher.doFinal(plaintext, 0, plaintext.length, ciphertext);

      byteCipherText = ciphertext;
    } catch (final GeneralSecurityException e) {
      throw new IllegalStateException("Missing basic functionality from Java runtime", e);
    }
    return byteCipherText;
  }
コード例 #27
0
 public static byte[] getShared(SecretKey key, PublicKey pubkey)
     throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException,
         NoSuchAlgorithmException, NoSuchPaddingException {
   Cipher cipher = Cipher.getInstance("RSA");
   cipher.init(Cipher.ENCRYPT_MODE, pubkey);
   return cipher.doFinal(key.getEncoded());
 }
コード例 #28
0
 public static byte[] encrypt(Key key, byte[] b)
     throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException,
         NoSuchAlgorithmException, NoSuchPaddingException {
   Cipher hasher = Cipher.getInstance("RSA");
   hasher.init(Cipher.ENCRYPT_MODE, key);
   return hasher.doFinal(b);
 }
コード例 #29
0
 public String[] receiveTransactionId(byte[] data)
     throws RemoteException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
         IllegalBlockSizeException, BadPaddingException {
   Cipher cipher = Cipher.getInstance("RSA");
   cipher.init(Cipher.DECRYPT_MODE, privateKey);
   byte[] cipherData = cipher.doFinal(data);
   String x = new String(cipherData);
   System.out.println(x);
   if (x.equals("e3050620f38846eeab342d293f13e043")) {
     String val = UUID.randomUUID().toString().replaceAll("-", "");
     transactionDetails[0] = val;
     System.out.println(transactionDetails[0]);
     String bits = "";
     Random r = new Random();
     for (int l = 0; l < 2048; l++) {
       int y = 0;
       if (r.nextBoolean()) y = 1;
       bits += y;
     }
     transactionDetails[1] = bits;
     System.out.println(transactionDetails[1]);
     System.out.println(transactionDetails);
   }
   return transactionDetails;
 }
コード例 #30
0
  public void writeSession(HttpServletRequest request, HttpServletResponse response)
      throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
          BadPaddingException, IllegalBlockSizeException {
    SparkHttpRequestWrapper sparkRequest = (SparkHttpRequestWrapper) request;
    if (!sparkRequest.sessionAccessed()) return;
    CookieSession session = (CookieSession) request.getSession();

    // serialize session
    byte[] sessionBytes = conf.asByteArray(session);

    // encrypt content
    final Cipher symmetricalCipher = Cipher.getInstance(symmetricEncryptionAlgorithm);
    symmetricalCipher.init(Cipher.ENCRYPT_MODE, this.symmetricEncryptionKey);
    byte[] encryptedBytes = symmetricalCipher.doFinal(sessionBytes);

    // sign content
    byte[] signature = sign(encryptedBytes);
    byte[] cookieContent = new byte[encryptedBytes.length + signature.length];

    System.arraycopy(encryptedBytes, 0, cookieContent, 0, encryptedBytes.length);
    System.arraycopy(
        signature, 0, cookieContent, cookieContent.length - signature.length, signature.length);

    String base64CookieContent = Base64.getEncoder().encodeToString(cookieContent);
    addCookie(base64CookieContent, response);
  }