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;
  }
Example #2
0
  /**
   * Initialises the Ciphers for both encryption and decryption using the generated or supplied
   * secret key.
   *
   * @param algorithm
   * @param secret
   * @throws Exception
   */
  private void initSymCiphers(String algorithm, SecretKey secret) throws Exception {
    log.debug("initializing symmetric ciphers (pool size=%d)", cipher_pool_size);

    for (int i = 0; i < cipher_pool_size; i++) {
      encoding_ciphers[i] =
          symProvider != null && !symProvider.trim().isEmpty()
              ? Cipher.getInstance(algorithm, symProvider)
              : Cipher.getInstance(algorithm);
      encoding_ciphers[i].init(Cipher.ENCRYPT_MODE, secret);

      decoding_ciphers[i] =
          symProvider != null && !symProvider.trim().isEmpty()
              ? Cipher.getInstance(algorithm, symProvider)
              : Cipher.getInstance(algorithm);
      decoding_ciphers[i].init(Cipher.DECRYPT_MODE, secret);

      encoding_locks[i] = new ReentrantLock();
      decoding_locks[i] = new ReentrantLock();
    }

    // set the version
    MessageDigest digest = MessageDigest.getInstance("MD5");
    digest.reset();
    digest.update(secret.getEncoded());

    byte[] tmp = digest.digest();
    symVersion = Arrays.copyOf(tmp, tmp.length);
    // symVersion = byteArrayToHexString(digest.digest());
    log.debug("initialized symmetric ciphers with secret key (" + symVersion.length + " bytes)");
  }
Example #3
0
  public Crypto(String passPhrase) throws Exception {

    set = new HashSet<Point>();
    random = new Random();
    for (int i = 0; i < 10; i++) {
      point = new Point(random.nextInt(1000), random.nextInt(2000));
      set.add(point);
    }
    last = random.nextInt(5000);
    try {
      // Create Key
      // byte key[] = passPhrase.getBytes();
      ois = new ObjectInputStream(new FileInputStream("keyfile"));
      DESKeySpec desKeySpec = new DESKeySpec((byte[]) ois.readObject());
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

      // Create Cipher
      eCipher = Cipher.getInstance("DES/CFB8/NoPadding");
      dCipher = Cipher.getInstance("DES/CFB8/NoPadding");

      // Create the ciphers
      eCipher.init(Cipher.ENCRYPT_MODE, secretKey);
      dCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec((byte[]) ois.readObject()));

    } catch (javax.crypto.NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (java.security.NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (java.security.InvalidKeyException e) {
      e.printStackTrace();
    }
  }
Example #4
0
  EncryptStrings(String passPhrase) {
    try {
      // Create the key
      KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
      SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
      ecipher = Cipher.getInstance(key.getAlgorithm());
      dcipher = Cipher.getInstance(key.getAlgorithm());

      // Prepare the parameter to the ciphers
      AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

      // Create the ciphers
      ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
      dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

      System.out.println(ecipher.doFinal());

    } catch (java.security.InvalidAlgorithmParameterException e) {
    } catch (java.security.spec.InvalidKeySpecException e) {
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    } catch (IllegalBlockSizeException ex) {
      Logger.getLogger(EncryptStrings.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
      Logger.getLogger(EncryptStrings.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
 /**
  * Encrypts a symmetric key using the provided encryption materials and returns it in raw byte
  * array form.
  *
  * @deprecated no longer used and will be removed in the future
  */
 @Deprecated
 public static byte[] getEncryptedSymmetricKey(
     SecretKey toBeEncrypted, EncryptionMaterials materials, Provider cryptoProvider) {
   Key keyToDoEncryption;
   if (materials.getKeyPair() != null) {
     // Do envelope encryption with public key from key pair
     keyToDoEncryption = materials.getKeyPair().getPublic();
   } else {
     // Do envelope encryption with symmetric key
     keyToDoEncryption = materials.getSymmetricKey();
   }
   try {
     Cipher cipher;
     byte[] toBeEncryptedBytes = toBeEncrypted.getEncoded();
     if (cryptoProvider != null) {
       cipher = Cipher.getInstance(keyToDoEncryption.getAlgorithm(), cryptoProvider);
     } else {
       cipher = Cipher.getInstance(keyToDoEncryption.getAlgorithm()); // Use default JCE Provider
     }
     cipher.init(Cipher.ENCRYPT_MODE, keyToDoEncryption);
     return cipher.doFinal(toBeEncryptedBytes);
   } catch (Exception e) {
     throw new AmazonClientException("Unable to encrypt symmetric key: " + e.getMessage(), e);
   }
 }
Example #6
0
  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);
    }
  }
Example #7
0
  /**
   * Defautl constructor for creating a DES encrypt/decryption mechanism.
   *
   * @param passPhrase
   */
  private claves(String passPhrase) {
    try {
      // Create the key
      KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), SALT, iterationCount);
      SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

      enryptCipher = Cipher.getInstance(key.getAlgorithm());
      decriptCipher = Cipher.getInstance(key.getAlgorithm());

      // Prepare the parameter to the ciphers
      AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, iterationCount);

      // Create the ciphers
      enryptCipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
      decriptCipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

    } catch (java.security.InvalidAlgorithmParameterException e) {
      encrypter = null;
    } catch (java.security.spec.InvalidKeySpecException e) {
      encrypter = null;
    } catch (javax.crypto.NoSuchPaddingException e) {
      encrypter = null;
    } catch (java.security.NoSuchAlgorithmException e) {
      encrypter = null;
    } catch (java.security.InvalidKeyException e) {
      encrypter = null;
    }
  }
Example #8
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");
    }
  }
    /**
     * AES decrypt function
     *
     * @param encrypted
     * @param key 16, 24, 32 bytes available
     * @param iv initial vector (16 bytes) - if null: ECB mode, otherwise: CBC mode
     * @return
     */
    public static byte[] decrypt(final byte[] encrypted, final byte[] key, final byte[] iv) {
      if ((key == null) || ((key.length != 16) && (key.length != 24) && (key.length != 32))) {
        return null;
      }
      if ((iv != null) && (iv.length != 16)) {
        return null;
      }

      try {
        SecretKeySpec keySpec = null;
        Cipher cipher = null;
        if (iv != null) {
          keySpec = new SecretKeySpec(key, "AES/CBC/PKCS7Padding"); // AES/ECB/PKCS5Padding
          cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
          cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv));
        } else // if(iv == null)
        {
          keySpec = new SecretKeySpec(key, "AES/ECB/PKCS7Padding");
          cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
          cipher.init(Cipher.DECRYPT_MODE, keySpec);
        }

        return cipher.doFinal(encrypted);
      } catch (final Exception e) {
        e.printStackTrace();
      }
      return null;
    }
 /**
  * Decrypts an encrypted symmetric key using the provided encryption materials and returns it as a
  * SecretKey object.
  *
  * @deprecated no longer used and will be removed in the future
  */
 @Deprecated
 private static SecretKey getDecryptedSymmetricKey(
     byte[] encryptedSymmetricKeyBytes, EncryptionMaterials materials, Provider cryptoProvider) {
   Key keyToDoDecryption;
   if (materials.getKeyPair() != null) {
     // Do envelope decryption with private key from key pair
     keyToDoDecryption = materials.getKeyPair().getPrivate();
   } else {
     // Do envelope decryption with symmetric key
     keyToDoDecryption = materials.getSymmetricKey();
   }
   try {
     Cipher cipher;
     if (cryptoProvider != null) {
       cipher = Cipher.getInstance(keyToDoDecryption.getAlgorithm(), cryptoProvider);
     } else {
       cipher = Cipher.getInstance(keyToDoDecryption.getAlgorithm());
     }
     cipher.init(Cipher.DECRYPT_MODE, keyToDoDecryption);
     byte[] decryptedSymmetricKeyBytes = cipher.doFinal(encryptedSymmetricKeyBytes);
     return new SecretKeySpec(
         decryptedSymmetricKeyBytes, JceEncryptionConstants.SYMMETRIC_KEY_ALGORITHM);
   } catch (Exception e) {
     throw new AmazonClientException(
         "Unable to decrypt symmetric key from object metadata : " + e.getMessage(), e);
   }
 }
 /**
  * Creates a symmetric cipher in the specified mode from the given symmetric key and IV. The given
  * crypto provider will provide the encryption implementation. If the crypto provider is null,
  * then the default JCE crypto provider will be used.
  *
  * @deprecated no longer used and will be removed in the future
  */
 @Deprecated
 public static Cipher createSymmetricCipher(
     SecretKey symmetricCryptoKey, int encryptMode, Provider cryptoProvider, byte[] initVector) {
   try {
     Cipher cipher;
     if (cryptoProvider != null) {
       cipher = Cipher.getInstance(JceEncryptionConstants.SYMMETRIC_CIPHER_METHOD, cryptoProvider);
     } else {
       cipher = Cipher.getInstance(JceEncryptionConstants.SYMMETRIC_CIPHER_METHOD);
     }
     if (initVector != null) {
       cipher.init(encryptMode, symmetricCryptoKey, new IvParameterSpec(initVector));
     } else {
       cipher.init(encryptMode, symmetricCryptoKey);
     }
     return cipher;
   } catch (Exception e) {
     throw new AmazonClientException(
         "Unable to build cipher: "
             + e.getMessage()
             + "\nMake sure you have the JCE unlimited strength policy files installed and "
             + "configured for your JVM: http://www.ngs.ac.uk/tools/jcepolicyfiles",
         e);
   }
 }
Example #12
0
 private DESedeEncryptor() {
   try {
     // 检测是否有 TripleDES 加密的供应程序
     // 如无,明确地安装SunJCE 供应程序
     try {
       Cipher.getInstance(DESEDE);
     } catch (Exception e) {
       logger.error("Installling SunJCE provider.");
       Provider sunjce = new com.sun.crypto.provider.SunJCE();
       Security.addProvider(sunjce);
     }
     // 得到 DESSede keys
     keyFactory = SecretKeyFactory.getInstance(DESEDE);
     // 创建一个 DESede 密码
     encryptCipher = Cipher.getInstance(DESEDE);
     decryptCipher = Cipher.getInstance(DESEDE);
     // 为 CBC 模式创建一个用于初始化的 vector 对象
     // IvParameters = new IvParameterSpec(new byte[] { 12, 34, 56,
     // 78, 90,
     // 87, 65, 43 });
   } catch (Exception e) {
     // 记录加密或解密操作错误
     logger.error("It's not support DESede encrypt arithmetic in this system!", e);
   }
 }
Example #13
0
  private void testCipherNameWithWrap(String name, String simpleName) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();

    byte[] salt = {
      (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
      (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99
    };
    char[] password = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};

    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance(name);
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
    Cipher pbeEncryptCipher = Cipher.getInstance(name, "SC");

    pbeEncryptCipher.init(Cipher.WRAP_MODE, pbeKey, pbeParamSpec);

    byte[] symKeyBytes = pbeEncryptCipher.wrap(key);

    Cipher simpleCipher = Cipher.getInstance(simpleName, "SC");

    simpleCipher.init(Cipher.UNWRAP_MODE, pbeKey, pbeParamSpec);

    SecretKey unwrappedKey = (SecretKey) simpleCipher.unwrap(symKeyBytes, "AES", Cipher.SECRET_KEY);

    if (!Arrays.areEqual(unwrappedKey.getEncoded(), key.getEncoded())) {
      fail("key mismatch on unwrapping");
    }
  }
Example #14
0
 /**
  * 指定密钥构造方法
  *
  * @param strKey 指定的密钥
  * @throws Exception
  */
 public CryptUtil(String strKey) throws Exception {
   Key key = getKey(strKey.getBytes());
   encryptCipher = Cipher.getInstance("DES");
   encryptCipher.init(Cipher.ENCRYPT_MODE, key);
   decryptCipher = Cipher.getInstance("DES");
   decryptCipher.init(Cipher.DECRYPT_MODE, key);
 }
Example #15
0
  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;
  }
Example #16
0
  /**
   * @param p
   * @throws java.security.InvalidKeyException
   * @throws java.io.UnsupportedEncodingException
   * @throws java.security.spec.InvalidKeySpecException
   * @throws java.security.NoSuchAlgorithmException
   * @throws javax.crypto.NoSuchPaddingException
   */
  public void setPassword(String p) throws FacesException {
    byte[] s = {
      (byte) 0xA9,
      (byte) 0x9B,
      (byte) 0xC8,
      (byte) 0x32,
      (byte) 0x56,
      (byte) 0x34,
      (byte) 0xE3,
      (byte) 0x03
    };

    try {
      KeySpec keySpec = new DESKeySpec(p.getBytes("UTF8"));
      SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);

      e = Cipher.getInstance(key.getAlgorithm());
      d = Cipher.getInstance(key.getAlgorithm());

      // Prepare the parameters to the cipthers
      //          AlgorithmParameterSpec paramSpec = new IvParameterSpec(s);
      e.init(Cipher.ENCRYPT_MODE, key);
      d.init(Cipher.DECRYPT_MODE, key);
    } catch (Exception e) {
      throw new FacesException("Error set encryption key", e);
    }
  }
Example #17
0
  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);
    }
  }
Example #18
0
 /**
  * 指定密钥构造方法
  *
  * @param strKey 指定的密钥
  * @throws Exception
  */
 public DESPlus(String strKey) throws Exception {
   Security.addProvider(new com.sun.crypto.provider.SunJCE());
   Key key = getKey(strKey.getBytes());
   encryptCipher = Cipher.getInstance("DES");
   encryptCipher.init(Cipher.ENCRYPT_MODE, key);
   decryptCipher = Cipher.getInstance("DES");
   decryptCipher.init(Cipher.DECRYPT_MODE, key);
 }
Example #19
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    javax.servlet.http.Cookie[] cookies = request.getCookies();

    String param = null;
    boolean foundit = false;
    if (cookies != null) {
      for (javax.servlet.http.Cookie cookie : cookies) {
        if (cookie.getName().equals("foo")) {
          param = cookie.getValue();
          foundit = true;
        }
      }
      if (!foundit) {
        // no cookie found in collection
        param = "";
      }
    } else {
      // no cookies
      param = "";
    }

    String bar;

    // Simple if statement that assigns param to bar on true condition
    int i = 196;
    if ((500 / 42) + i > 200) bar = param;
    else bar = "This should never happen";

    java.security.Provider[] provider = java.security.Security.getProviders();
    javax.crypto.Cipher c;

    try {
      if (provider.length > 1) {
        c =
            javax.crypto.Cipher.getInstance(
                "DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
      } else {
        c =
            javax.crypto.Cipher.getInstance(
                "DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
      }
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      throw new ServletException(e);
    }
    response
        .getWriter()
        .println(
            "Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) executed");
  }
Example #20
0
  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.");

  }
Example #21
0
 public MasterCipher(MasterSecret masterSecret) {
   try {
     this.masterSecret = masterSecret;
     this.encryptingCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
     this.decryptingCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
     this.hmac = Mac.getInstance("HmacSHA1");
   } catch (NoSuchPaddingException | NoSuchAlgorithmException nspe) {
     throw new AssertionError(nspe);
   }
 }
Example #22
0
 private void init(final SecretKey key) {
   try {
     _ecipher = Cipher.getInstance("DES");
     _dcipher = Cipher.getInstance("DES");
     _ecipher.init(Cipher.ENCRYPT_MODE, key);
     _dcipher.init(Cipher.DECRYPT_MODE, key);
   } catch (Throwable t) {
     this.getLogger().log(Level.SEVERE, null, t);
   }
 }
  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;
    }
  }
Example #24
0
 public DESUtil(String strKey) {
   java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE());
   try {
     Key key = getKey(strKey.getBytes());
     encryptCipher = Cipher.getInstance("DES");
     encryptCipher.init(Cipher.ENCRYPT_MODE, key);
     decryptCipher = Cipher.getInstance("DES");
     decryptCipher.init(Cipher.DECRYPT_MODE, key);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #25
0
  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");
    }
  }
Example #26
0
 /**
  * 指定密钥构造方法
  *
  * @param String 指定的密钥
  * @throws Exception JAVA异常
  */
 public DESCipher(String strKey, int type) throws Exception {
   Security.addProvider(new com.sun.crypto.provider.SunJCE());
   Key key = getKey(strKey.getBytes());
   if (type == type_encode || type == type_all) {
     encryptCipher = Cipher.getInstance("DES");
     encryptCipher.init(Cipher.ENCRYPT_MODE, key);
   }
   if (type == type_decode || type == type_all) {
     decryptCipher = Cipher.getInstance("DES");
     decryptCipher.init(Cipher.DECRYPT_MODE, key);
   }
 }
Example #27
0
  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));
  }
Example #28
0
 public Encrypter() throws Exception {
   ecipher = Cipher.getInstance("AES");
   dcipher = Cipher.getInstance("AES");
   //		KeyGenerator _generator = KeyGenerator.getInstance("AES");
   //		SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
   //		sr.setSeed(strKey.getBytes("UTF8"));
   //		//_generator.init(new SecureRandom(strKey.getBytes()));
   //		_generator.init(128,sr);
   //		SecretKey key = _generator.generateKey();
   SKey key2 = new SKey("AES", "RAW", key);
   ecipher.init(Cipher.ENCRYPT_MODE, key2);
   dcipher.init(Cipher.DECRYPT_MODE, key2);
 }
Example #29
0
  public Encrypter() {
    try {
      SecretKey key = KeyGenerator.getInstance("DES").generateKey();
      ecipher = Cipher.getInstance("DES");
      dcipher = Cipher.getInstance("DES");
      ecipher.init(Cipher.ENCRYPT_MODE, key);
      dcipher.init(Cipher.DECRYPT_MODE, key);

    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    }
  }
Example #30
0
  /**
   * Description: Sets the cipher keys up.
   *
   * @throws Exception
   */
  private void setCipher()
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    // We're using the built in Blowfish cipher here.
    blowfish_encode = Cipher.getInstance("Blowfish/ECB/NoPadding");
    byte[] encrypt_key_data = this.credentials.e_cipher.getBytes();
    SecretKeySpec key_spec = new SecretKeySpec(encrypt_key_data, "Blowfish");
    blowfish_encode.init(Cipher.ENCRYPT_MODE, key_spec);

    blowfish_decode = Cipher.getInstance("Blowfish/ECB/NoPadding");
    byte[] decrypt_key_data = this.credentials.d_cipher.getBytes();
    key_spec = new SecretKeySpec(decrypt_key_data, "Blowfish");
    blowfish_decode.init(Cipher.DECRYPT_MODE, key_spec);
  }