@param _inputText Text to be encrypted or decrypted @param _encryptionKey Encryption key to used for encryption / decryption @param _mode specify the mode encryption / decryption @param _initVector Initialization vector @return encrypted or decrypted string ba
(String _inputText, String _encryptionKey,
EncryptMode _mode, String _initVector)
| 102 | * @throws BadPaddingException |
| 103 | */ |
| 104 | private String encryptDecrypt(String _inputText, String _encryptionKey, |
| 105 | EncryptMode _mode, String _initVector) throws UnsupportedEncodingException, |
| 106 | InvalidKeyException, InvalidAlgorithmParameterException, |
| 107 | IllegalBlockSizeException, BadPaddingException { |
| 108 | String _out = "";// output string |
| 109 | //_encryptionKey = md5(_encryptionKey); |
| 110 | //System.out.println("key="+_encryptionKey); |
| 111 | |
| 112 | int len = _encryptionKey.getBytes("UTF-8").length; // length of the key provided |
| 113 | |
| 114 | if (_encryptionKey.getBytes("UTF-8").length > _key.length) |
| 115 | len = _key.length; |
| 116 | |
| 117 | int ivlen = _initVector.getBytes("UTF-8").length; |
| 118 | |
| 119 | if(_initVector.getBytes("UTF-8").length > _iv.length) |
| 120 | ivlen = _iv.length; |
| 121 | |
| 122 | System.arraycopy(_encryptionKey.getBytes("UTF-8"), 0, _key, 0, len); |
| 123 | System.arraycopy(_initVector.getBytes("UTF-8"), 0, _iv, 0, ivlen); |
| 124 | //KeyGenerator _keyGen = KeyGenerator.getInstance("AES"); |
| 125 | //_keyGen.init(128); |
| 126 | |
| 127 | SecretKeySpec keySpec = new SecretKeySpec(_key, "AES"); // Create a new SecretKeySpec |
| 128 | // for the |
| 129 | // specified key |
| 130 | // data and |
| 131 | // algorithm |
| 132 | // name. |
| 133 | |
| 134 | IvParameterSpec ivSpec = new IvParameterSpec(_iv); // Create a new |
| 135 | // IvParameterSpec |
| 136 | // instance with the |
| 137 | // bytes from the |
| 138 | // specified buffer |
| 139 | // iv used as |
| 140 | // initialization |
| 141 | // vector. |
| 142 | |
| 143 | // encryption |
| 144 | if (_mode.equals(EncryptMode.ENCRYPT)) { |
| 145 | // Potentially insecure random numbers on Android 4.3 and older. |
| 146 | // Read |
| 147 | // https://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html |
| 148 | // for more info. |
| 149 | _cx.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);// Initialize this cipher instance |
| 150 | byte[] results = _cx.doFinal(_inputText.getBytes("UTF-8")); // Finish |
| 151 | // multi-part |
| 152 | // transformation |
| 153 | // (encryption) |
| 154 | _out = Base64.getEncoder().encodeToString(results); // ciphertext |
| 155 | // output |
| 156 | } |
| 157 | |
| 158 | // decryption |
| 159 | if (_mode.equals(EncryptMode.DECRYPT)) { |
| 160 | _cx.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);// Initialize this ipher instance |
| 161 |