/**
   * Decrypts a String encrypted encrypted by the encrypt(String, Key) function.
   *
   * @param encryptedVersion The encrypted string
   * @param keyData The byte[] representation of the Key used in encryption.
   * @return The decrypted String.
   * @throws EncryptionException
   * @throws InvalidKeyException
   * @throws NoSuchAlgorithmException
   * @throws NoSuchPaddingException
   * @throws IllegalBlockSizeException
   * @throws BadPaddingException
   * @throws IOException
   */
  public static byte[] decrypt(byte[] encryptedVersion, Key salt) throws EncryptionException {
    // Get a cipher object.
    byte[] result = null;

    Cipher cipher;
    try {
      cipher = Cipher.getInstance(EncryptionAlgorithm.DES.toString());

      cipher.init(Cipher.DECRYPT_MODE, salt);

      result = cipher.doFinal(encryptedVersion);

    } catch (NoSuchAlgorithmException e) {
      throw new EncryptionException(e);
    } catch (NoSuchPaddingException e) {
      throw new EncryptionException(e);
    } catch (InvalidKeyException e) {
      throw new EncryptionException(e);
    } catch (IllegalBlockSizeException e) {
      throw new EncryptionException(e);
    } catch (BadPaddingException e) {
      throw new EncryptionException(e);
    }
    return result;
  }
  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);
  }
Example #3
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);
 }
Example #4
0
  @Kroll.method
  public String decode(HashMap args) {
    // decode string back to plain text
    //
    KrollDict arg = new KrollDict(args);
    String txt = arg.getString("cipherText");
    byte[] bytesEncoded = Base64.decode(txt, 0);
    String keyString = arg.getString("privateKey");
    PrivateKey key;

    try {
      byte[] encodedKey = Base64.decode(keyString, 0);
      PKCS8EncodedKeySpec x509KeySpec = new PKCS8EncodedKeySpec(encodedKey);
      KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
      key = keyFact.generatePrivate(x509KeySpec);
    } catch (Exception e) {
      return "error key";
    }

    byte[] decodedBytes = null;

    try {
      Cipher c = Cipher.getInstance("RSA");
      c.init(Cipher.DECRYPT_MODE, key);
      decodedBytes = c.doFinal(bytesEncoded);
    } catch (Exception e) {
      Log.e(TAG, "RSA decryption error " + e.toString());
      return "error";
    }
    return new String(decodedBytes);
  }
  /**
   * Encrypts the provided String and returns the cipher text.
   *
   * @param text the String to encrypt
   * @return the encrypted String
   * @throws InvalidKeyException
   * @throws BadPaddingException
   * @throws IllegalBlockSizeException
   */
  public String encrypt(String text)
      throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    cipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] encryptedText = cipher.doFinal(text.getBytes());

    return new String(Base64.encodeBase64(encryptedText));
  }
Example #6
0
 /**
  * This method: Encrypts bytes using a cipher. Generates MAC for intialization vector of the
  * cipher Generates MAC for encrypted data Returns a byte array consisting of the following
  * concatenated together: |MAC for cnrypted Data | MAC for Init Vector | Encrypted Data |
  *
  * @param bytes The byte array to be encrypted.
  * @return the encrypted byte array.
  */
 public byte[] encrypt(byte[] bytes) {
   byte[] securedata = null;
   try {
     // Generate IV
     SecureRandom rand = new SecureRandom();
     byte[] iv = new byte[16];
     rand.nextBytes(iv);
     IvParameterSpec ivspec = new IvParameterSpec(iv);
     Cipher encryptCipher = Cipher.getInstance(CIPHER_CODE);
     encryptCipher.init(Cipher.ENCRYPT_MODE, sk, ivspec);
     Mac encryptMac = Mac.getInstance(MAC_CODE);
     encryptMac.init(sk);
     encryptMac.update(iv);
     // encrypt the plaintext
     byte[] encdata = encryptCipher.doFinal(bytes);
     byte[] macBytes = encryptMac.doFinal(encdata);
     byte[] tmp = concatBytes(macBytes, iv);
     securedata = concatBytes(tmp, encdata);
   } catch (NoSuchAlgorithmException
       | NoSuchPaddingException
       | InvalidKeyException
       | InvalidAlgorithmParameterException
       | IllegalStateException
       | IllegalBlockSizeException
       | BadPaddingException e) {
     if (LOGGER.isLoggable(Level.SEVERE)) {
       LOGGER.log(
           Level.SEVERE,
           "Unexpected exception initializing encryption." + "  No encryption will be performed.",
           e);
     }
     return null;
   }
   return securedata;
 }
  /** {@inheritDoc} */
  @Override
  public byte[] encrypt(final byte[] bytes) throws EncyptionException {
    try {
      final javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding");
      cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, this.secretKey);

      final AlgorithmParameters params = cipher.getParameters();
      final byte[] ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
      final byte[] dataBytes = cipher.doFinal(bytes);
      final byte[] secret = ArrayOfBytesType.TYPE.toBytes(ivBytes, dataBytes);
      return secret;
    } catch (final NoSuchAlgorithmException problem) {
      throw new EncyptionException(problem);
    } catch (final NoSuchPaddingException problem) {
      throw new EncyptionException(problem);
    } catch (final InvalidKeyException problem) {
      throw new EncyptionException(problem);
    } catch (final InvalidParameterSpecException problem) {
      throw new EncyptionException(problem);
    } catch (final IllegalBlockSizeException problem) {
      throw new EncyptionException(problem);
    } catch (final BadPaddingException problem) {
      throw new EncyptionException(problem);
    }
  }
 private static byte[] encryptPassword(byte[] password, byte[] salt) {
   try {
     byte[] encryptedPassword = null;
     PBEKeySpec pbeKeySpec = new PBEKeySpec(getPassword(), salt, 1024, 256);
     SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM);
     SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
     PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 10);
     Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
     cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
     encryptedPassword = cipher.doFinal(password);
     return encryptedPassword;
   } catch (NoSuchAlgorithmException e) {
     LogHelper.log(e);
   } catch (InvalidKeySpecException e) {
     LogHelper.log(e);
   } catch (InvalidKeyException e) {
     LogHelper.log(e);
   } catch (IllegalBlockSizeException e) {
     LogHelper.log(e);
   } catch (BadPaddingException e) {
     LogHelper.log(e);
   } catch (NoSuchPaddingException e) {
     LogHelper.log(e);
   } catch (InvalidAlgorithmParameterException e) {
     LogHelper.log(e);
   }
   return null;
 }
Example #9
0
  /**
   * 解密
   *
   * @param content 密文
   * @param key 商户私钥
   * @return 解密后的字符串
   */
  public static String decrypt(String content, String key) throws Exception {
    PrivateKey prikey = getPrivateKey(key);

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, prikey);

    InputStream ins = new ByteArrayInputStream(Base64.decode(content));
    ByteArrayOutputStream writer = new ByteArrayOutputStream();
    // rsa解密的字节大小最多是128,将需要解密的内容,按128位拆开解密
    byte[] buf = new byte[128];
    int bufl;

    while ((bufl = ins.read(buf)) != -1) {
      byte[] block = null;

      if (buf.length == bufl) {
        block = buf;
      } else {
        block = new byte[bufl];
        for (int i = 0; i < bufl; i++) {
          block[i] = buf[i];
        }
      }

      writer.write(cipher.doFinal(block));
    }

    return new String(writer.toByteArray(), "utf-8");
  }
 private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
   SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
   Cipher cipher = Cipher.getInstance("AES");
   cipher.init(Cipher.DECRYPT_MODE, skeySpec);
   byte[] decrypted = cipher.doFinal(encrypted);
   return decrypted;
 }
Example #11
0
  /**
   * Decrypt an encrypted PKCS 8 format private key.
   *
   * <p>Based on ghstark's post on Aug 6, 2006 at
   * http://forums.sun.com/thread.jspa?threadID=758133&messageID=4330949
   *
   * @param encryptedPrivateKey The raw data of the private key
   * @param keyFile The file containing the private key
   */
  private KeySpec decryptPrivateKey(byte[] encryptedPrivateKey, String keyPassword)
      throws GeneralSecurityException {
    EncryptedPrivateKeyInfo epkInfo;
    try {
      epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey);
    } catch (IOException ex) {
      // Probably not an encrypted key.
      return null;
    }

    char[] keyPasswd = keyPassword.toCharArray();

    SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
    Key key = skFactory.generateSecret(new PBEKeySpec(keyPasswd));

    Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());

    try {
      return epkInfo.getKeySpec(cipher);
    } catch (InvalidKeySpecException ex) {
      getLogger().error("signapk: Password for private key may be bad.");
      throw ex;
    }
  }
Example #12
0
  PGPDataDecryptor createDataDecryptor(boolean withIntegrityPacket, int encAlgorithm, byte[] key)
      throws PGPException {
    try {
      SecretKey secretKey = new SecretKeySpec(key, PGPUtil.getSymmetricCipherName(encAlgorithm));

      final Cipher c = createStreamCipher(encAlgorithm, withIntegrityPacket);

      if (withIntegrityPacket) {
        byte[] iv = new byte[c.getBlockSize()];

        c.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
      } else {
        c.init(Cipher.DECRYPT_MODE, secretKey);
      }

      return new PGPDataDecryptor() {
        public InputStream getInputStream(InputStream in) {
          return new CipherInputStream(in, c);
        }

        public int getBlockSize() {
          return c.getBlockSize();
        }

        public PGPDigestCalculator getIntegrityCalculator() {
          return new SHA1PGPDigestCalculator();
        }
      };
    } catch (PGPException e) {
      throw e;
    } catch (Exception e) {
      throw new PGPException("Exception creating cipher", e);
    }
  }
Example #13
0
  /**
   * 解密
   *
   * @param key 解密的密钥
   * @param raw 已经加密的数据
   * @return 解密后的明文
   * @throws Exception
   */
  public static byte[] decrypt(Key key, byte[] raw) throws Exception {

    try {

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

      cipher.init(Cipher.DECRYPT_MODE, key);

      int blockSize = cipher.getBlockSize();

      ByteArrayOutputStream bout = new ByteArrayOutputStream(64);

      int j = 0;

      while (raw.length - j * blockSize > 0) {

        bout.write(cipher.doFinal(raw, j * blockSize, blockSize));

        j++;
      }

      return bout.toByteArray();

    } catch (Exception e) {

      throw new Exception(e.getMessage());
    }
  }
Example #14
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");
    }
  }
Example #15
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);
   }
 }
  /**
   * Encode password using DES encryption with given challenge.
   *
   * @param challenge a random set of bytes.
   * @param password a password
   * @return DES hash of password and challenge
   */
  public ByteBuffer encodePassword(ByteBuffer challenge, String password) {
    if (challenge.length != 16)
      throw new RuntimeException("Challenge must be exactly 16 bytes long.");

    // VNC password consist of up to eight ASCII characters.
    byte[] key = {0, 0, 0, 0, 0, 0, 0, 0}; // Padding
    byte[] passwordAsciiBytes = password.getBytes(RfbConstants.US_ASCII_CHARSET);
    System.arraycopy(passwordAsciiBytes, 0, key, 0, Math.min(password.length(), 8));

    // Flip bytes (reverse bits) in key
    for (int i = 0; i < key.length; i++) {
      key[i] = flipByte(key[i]);
    }

    try {
      KeySpec desKeySpec = new DESKeySpec(key);
      SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
      SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
      Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);

      ByteBuffer buf =
          new ByteBuffer(cipher.doFinal(challenge.data, challenge.offset, challenge.length));

      return buf;
    } catch (Exception e) {
      throw new RuntimeException("Cannot encode password.", e);
    }
  }
  public static String encrypt(String originalText, String password) {
    String enc = "";
    try {
      // cara penggunaan JCE u/ melakukan enkripsi berdasarkan metode enkripsi PBE, yg dipilih
      // (tidak
      // mesti PBEWithMD5AndDES
      PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(METHOD);
      SecretKey secretKey = keyFactory.generateSecret(keySpec);
      PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount);
      cipher = Cipher.getInstance(METHOD);
      cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
      outputArray = originalText.getBytes(encoding);
      cryptedText = new ByteArrayOutputStream();
      CipherOutputStream out = new CipherOutputStream(cryptedText, cipher);
      out.write(outputArray);
      out.flush();
      out.close();
      return cryptedText.toString();

    } catch (IOException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAlgorithmParameterException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "error";
  }
Example #18
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");
    }
  }
Example #19
0
  /**
   * 加密(使用DES算法)
   *
   * @param txt 需要加密的文本
   * @param key 密钥
   * @return 成功加密的文本
   * @throws InvalidKeySpecException
   * @throws InvalidKeyException
   * @throws NoSuchPaddingException
   * @throws IllegalBlockSizeException
   * @throws BadPaddingException
   */
  private static String enCrypto(String txt, String key)
      throws InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException,
          IllegalBlockSizeException, BadPaddingException {
    StringBuffer sb = new StringBuffer();
    DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
    SecretKeyFactory skeyFactory = null;
    Cipher cipher = null;
    try {
      skeyFactory = SecretKeyFactory.getInstance("DES");
      cipher = Cipher.getInstance("DES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    SecretKey deskey = skeyFactory != null ? skeyFactory.generateSecret(desKeySpec) : null;
    if (cipher != null) {
      cipher.init(Cipher.ENCRYPT_MODE, deskey);
    }
    byte[] cipherText = cipher != null ? cipher.doFinal(txt.getBytes()) : new byte[0];
    for (int n = 0; n < cipherText.length; n++) {
      String stmp = (java.lang.Integer.toHexString(cipherText[n] & 0XFF));

      if (stmp.length() == 1) {
        sb.append("0" + stmp);
      } else {
        sb.append(stmp);
      }
    }
    return sb.toString().toUpperCase();
  }
Example #20
0
 public byte[] readPrivateKeyToPKCSBytes(char[] encpass, String salt, String iv, String keyData)
     throws GeneralSecurityException {
   Key key = getKeyDecryptionKey(encpass, Base64.decode(salt));
   Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", PROVIDER_NAME);
   cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(Base64.decode(iv)));
   return cipher.doFinal(Base64.decode(keyData));
 }
  /** {@inheritDoc} */
  @Override
  public byte[] decrypt(final byte[] bytes) {
    final byte[][] secret = ArrayOfBytesType.TYPE.fromBytes(bytes);
    final byte[] ivBytes = secret[0];
    final byte[] dataBytes = secret[1];

    try {
      final javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding");
      final IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
      cipher.init(javax.crypto.Cipher.DECRYPT_MODE, this.secretKey, ivSpec);
      final byte[] decryptedBytes = cipher.doFinal(dataBytes);
      return decryptedBytes;
    } catch (final NoSuchAlgorithmException problem) {
      throw new EncyptionException(problem);
    } catch (final NoSuchPaddingException problem) {
      throw new EncyptionException(problem);
    } catch (final InvalidKeyException problem) {
      throw new EncyptionException(problem);
    } catch (final InvalidAlgorithmParameterException problem) {
      throw new EncyptionException(problem);
    } catch (final IllegalBlockSizeException problem) {
      throw new EncyptionException(problem);
    } catch (final BadPaddingException problem) {
      throw new EncyptionException(problem);
    }
  }
Example #22
0
 public Key unwrapSecretKey(RSAPrivateKey privKey, String wrapped)
     throws GeneralSecurityException {
   byte[] wrappedBytes = Base64.decode(wrapped);
   Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", PROVIDER_NAME);
   cipher.init(Cipher.UNWRAP_MODE, privKey);
   return cipher.unwrap(wrappedBytes, "AES", Cipher.SECRET_KEY);
 }
Example #23
0
  @Kroll.method
  public String encode(HashMap args) {
    // encode text to cipher text
    //
    KrollDict arg = new KrollDict(args);
    String txt = arg.getString("plainText");
    String keyString = arg.getString("publicKey");
    byte[] encodedBytes = null;
    Key key;

    try {
      byte[] encodedKey = Base64.decode(keyString, 0);
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encodedKey);
      KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
      key = keyFact.generatePublic(x509KeySpec);
    } catch (Exception e) {
      return "error key";
    }

    try {
      Cipher c = Cipher.getInstance("RSA");
      c.init(Cipher.ENCRYPT_MODE, key);
      encodedBytes = c.doFinal(txt.getBytes());
    } catch (Exception e) {
      Log.e(TAG, "RSA encryption error " + e.toString());
    }

    return Base64.encodeToString(encodedBytes, Base64.NO_WRAP);
  }
 /**
  * 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);
   }
 }
 /**
  * Decrypts the provided and String and returns the unencrypted String.
  *
  * @param cipherText the encrypted text to decrypt.
  * @return the unencrypted text
  * @throws InvalidKeyException
  * @throws BadPaddingException
  * @throws IllegalBlockSizeException
  */
 public String decrypt(String cipherText)
     throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
   cipher.init(Cipher.DECRYPT_MODE, aesKey);
   byte[] decodeBase64 = Base64.decodeBase64(cipherText.getBytes());
   String decryptedText = new String(cipher.doFinal(decodeBase64));
   return decryptedText;
 }
 /**
  * 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);
   }
 }
 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;
 }
 /**
  * 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);
   }
 }
Example #29
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());
 }
  /**
   * Decryption.
   *
   * @param data the data to be decrypted
   * @return the decrypted data
   * @throws Exception if necessary
   */
  @Override
  public byte[] internalDecrypt(byte[] data) throws Exception {
    Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParam);

    return cipher.doFinal(data);
  }