Reputation: 183
I´m very new to both the Android platform and encryption, so bear with me. I need to call a webservice which requires me to encrypt a parameter before calling it. I have received a specification which reads:
"We use AES to encrypt. Settings for the encryption follow:
Key: PublicKey12345678910
Number of bits: 128
Padding: PKCS #7
Cipher: Cipher Block Chaining (CBC)"
Now, my problem is probably a lack of basic understanding of the encryption process. I have my public key, but what do I do with it? I have tried to find an answer online but all my efforts seem to result in either the wrong encrypted key or very often an "InvalidKeyLengthException, key not 128, 196 or 256 bits" (or something in that general direction). My most recent effort, which borrows heavily from an answer here on stack, looks like this:
String input = "TheParameterIWantToEncrypt";
String secretID = "PublicKey12345678910";
char[] inputChars = input.toCharArray();
char[] pswChars = secretID.toCharArray();
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES", new BouncyCastleProvider());
KeySpec spec = new PBEKeySpec(pswChars);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal(input.getBytes());
System.out.println(new String(ciphertext));
Could someone explain to me in which order to do the things in the supplied specification? Also, any code implementing this behavior on the Java/Android platform would also be much obliged.
Upvotes: 0
Views: 697
Reputation: 95519
Forget, for a moment, the implementation details, and let's focus on things at a higher level. If you perform the encryption in this manner, your private key will be stored somewhere in the program or in the data used by the program in a way that could easily be extracted, compromising the encryption.
By contrast, if you use HTTPS (which is a very standard way to create an encrypted session), there will be well-tested and well-studied process whereby an asymmetric cipher is used to establish private keys that are then used to create an encrypted channel (usually using 128-bit AES encryption).
You should really push back on whoever is providing you with this webservice to offer it over a standard HTTPS connection for the encryption, rather than relying on encrypting individual fields like this.
Upvotes: 1