Ниже приведен код для Шифрование в Java
и Расшифровка для iOS (Swift и Android (Kotlin) . Это хорошо работает, но я все еще открыт для лучшего решения.
Java-код
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class EncryptionUtils {
private static String ENCRYPTION_KEY = "1234512345123456";
public static void main(String[] args) {
String encyString = new EncryptionUtils().encrypted("HJUSER153");
System.out.println("Encrypted String:" + encyString);
}
public String encrypted(String strToEncrypt) {
try {
IvParameterSpec ivspec = new IvParameterSpec(ENCRYPTION_KEY.getBytes());
SecretKeySpec keyspec = new SecretKeySpec(ENCRYPTION_KEY.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
//encrypted = cipher.doFinal(text.getBytes());
} catch (Exception e) {
System.out.println("\nException while encrypting " + strToEncrypt + " \nerror: " + e.getMessage());
}
return null;
}
}
iOS Swift Code
Добавить это в файл pod -
под 'CryptoSwift'
import CryptoSwift
func decrypt(input:String)->String?{
let key = "1234512345123456"
do{
let d=Data(base64Encoded: input)
let decrypted = try AES(key: key, iv: key, padding: .pkcs5).decrypt(
d!.bytes)
return String(data: Data(decrypted), encoding: .utf8)
}catch{
}
return nil
}
Android
import android.util.Base64
import java.security.NoSuchAlgorithmException
import javax.crypto.Cipher
import javax.crypto.NoSuchPaddingException
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
class CypherHelper {
private var ivspec: IvParameterSpec? = null
private var keyspec: SecretKeySpec? = null
private var cipher: Cipher? = null
private val ENCRYPTION_KEY: String = "1234567890123456"
init {
ivspec = IvParameterSpec(ENCRYPTION_KEY.toByteArray(Charsets.UTF_8))
keyspec = SecretKeySpec(ENCRYPTION_KEY.toByteArray(), "AES")
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
} catch (e: NoSuchPaddingException) {
e.printStackTrace()
}
}
fun decrypt(valueToDecrypt: String): String {
var decryptValue: String = ""
val enc = CypherHelper()
if (valueToDecrypt.isEmpty())
decryptValue = String(enc.decryptInternal(valueToDecrypt)!!)
return decryptValue
}
private fun decryptInternal(code: String?): ByteArray? {
if (code == null || code.isEmpty()) {
throw Exception("Empty string")
}
var decrypted: ByteArray? = null
try {
cipher?.init(Cipher.DECRYPT_MODE, keyspec, ivspec)
decrypted = cipher?.doFinal(Base64.decode(code, Base64.DEFAULT))
} catch (e: Exception) {
throw Exception("[decrypt] " + e.message)
}
return decrypted
}
}