Solution!
I came here and did well!
p>
Code to send PublicKey (SERVER SIDE):
PublicKey publicKey = RSA.getPublicKey();
KeyFactory fact = KeyFactory.getInstance("RSA");
X509EncodedKeySpec spec = fact.getKeySpec(publicKey,X509EncodedKeySpec.class);
String x = Base64.encode(spec.getEncoded());
return x; // retorna String
Code to create a PublicKey through a String (ANDROID APP SIDE)
String publicKeyString = x;
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(publicKeyString, Base64.DEFAULT));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(publicSpec);
Code to create a secret key with AES (ANDROID APP SIDE):
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();
Code to encrypt the text with the secret key (ANDROID APP SIDE):
SecretKeySpec skeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return Base64.encodeToString(encrypted); //retorna String
Code to encrypt the secret key with the publicKey (ANDROID APP SIDE):
Cipher cipher2 = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher2.init(Cipher.ENCRYPT_MODE, publicKey);
String encryptedSecretKey = Base64.encodeToString(cipher2.doFinal(secretKey.getEncoded()), Base64.DEFAULT);
return encryptedSecretKey;
-------------------------------- SEND ciphertext and encrypted key to the server ------ ----------------------
Code to decipher secret key (SERVER SIDE)
PrivateKey chavePrivada;
byte[] texto = Bse64.decode(texto_cifrado)
byte[] dectyptedSecKey = {};
try {
//"RSA/ECB/OAEPWithSHA1AndMGF1Padding"
Cipher cipher =Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
// Decriptografa o texto puro usando a chave Privada
cipher.init(Cipher.DECRYPT_MODE, chavePrivada);
dectyptedSecKey = cipher.doFinal(texto);
} catch (Exception ex) {
ex.printStackTrace();
}
return dectyptedSecKey;
Code to create a secret key by one byte [] (SERVER SIDE):
secretKey = new SecretKeySpec(dectyptedSecKey, 0, dectyptedSecKey.length, "AES");
Code to decrypt ciphertext with secret key (SERVER SIDE):
raw = secretKey.getEncoded();
encrypted = Base64.decode(dados);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted); // retorna String TEXTO ORIGINAL