Last active
December 11, 2018 19:36
-
-
Save mumayank/0465cbfd10c0755ea4c0d4835709b851 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ClientEncrypt { | |
private static String publicKeyString = "<your_public_key_here>"; | |
public static void main (String args[]) { | |
try { | |
// 1. generate secret key using AES | |
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); | |
keyGenerator.init(128); // AES is currently available in three key sizes: 128, 192 and 256 bits.The design and strength of all key lengths of the AES algorithm are sufficient to protect classified information up to the SECRET level | |
SecretKey secretKey = keyGenerator.generateKey(); | |
// 2. get string which needs to be encrypted | |
String text = "<your_string_which_needs_to_be_encrypted_here>"; | |
// 3. encrypt string using secret key | |
byte[] raw = secretKey.getEncoded(); | |
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); | |
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); | |
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16])); | |
String cipherTextString = Base64.encodeToString(cipher.doFinal(text.getBytes(Charset.forName("UTF-8"))), Base64.DEFAULT); | |
// 4. get public key | |
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(publicKeyString, Base64.DEFAULT)); | |
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); | |
PublicKey publicKey = keyFactory.generatePublic(publicSpec); | |
// 6. encrypt secret key using public key | |
Cipher cipher2 = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); | |
cipher2.init(Cipher.ENCRYPT_MODE, publicKey); | |
String encryptedSecretKey = Base64.encodeToString(cipher2.doFinal(secretKey.getEncoded()), Base64.DEFAULT); | |
// 7. pass cipherTextString (encypted sensitive data) and encryptedSecretKey to your server via your preferred way. | |
// Tips: | |
// You may use JSON to combine both the strings under 1 object. | |
// You may use a volley call to send this data to your server. | |
} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException | InvalidAlgorithmParameterException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment