How to encrypt in Java and decrypt in Android and iOS

荒凉一梦 提交于 2020-01-12 04:04:19

问题


I have a Linux server running a Java-jar file that encrypts several files.

The Android and iPhone App download that file and shall decrypt it. What algorithm I have to use to do so?

I recognized that the algorithms I used in Java do not work in Android. What I did in Java was:

private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(clear);
    return encrypted;
}

what didn't work in above code? Any alternatives?


回答1:


iOS:

I use NSString+AESCrypt (https://github.com/Gurpartap/AESCrypt-ObjC)

Sample:

NSString* encrypted = [plainText AES256EncryptWithKey:@"MyEncryptionKey"];
NSString* decrypted = [encrypted AES256DecryptWithKey:@"MyEncryptionKey"];

Android (AES256Cipher - https://gist.github.com/dealforest/1949873):

Encrypt:

String base64Text="";
try {
    String key = "MyEncryptionKey";
    byte[] keyBytes = key.getBytes("UTF-8");
    byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    byte[] cipherData;

    //############## Request(crypt) ##############
    cipherData = AES256Cipher.encrypt(ivBytes, keyBytes, passval1.getBytes("UTF-8"));
    base64Text = Base64.encodeToString(cipherData, Base64.DEFAULT);
}
catch ( Exception e ) {
    e.printStackTrace();
}        

Decrypt:

String base64Text="";
String plainText="";
try {
    String key = "MyEncryptionKey";
    byte[] keyBytes = key.getBytes("UTF-8");
    byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    byte[] cipherData;

    //############## Response(decrypt) ##############
base64Text = User.__currentUser.getPasscode();
    cipherData = AES256Cipher.decrypt(ivBytes, keyBytes, Base64.decode(base64Text.getBytes("UTF-8"), Base64.DEFAULT));
    plainText = new String(cipherData, "UTF-8");            
}
catch ( Exception e )
{
    e.printStackTrace();
}



回答2:


The link below gives a nice example of encryption and decryption using Symmetric key encryption.

The symmetric key used is a custom plain text. This helps if we need to to decrypt using a IOS device. The example uses a AES 128 bit encryption. Note that it uses IV parameters. Since the encryption is 128 bit the length of the key should be 16.

On Android side the same method implementations can be used since the language is Java. In IOS CommonCryptor.h can be used for encryption decryption.

http://www.java-redefined.com/2015/06/symmetric-key-encryption-ios-java.html



来源:https://stackoverflow.com/questions/20531329/how-to-encrypt-in-java-and-decrypt-in-android-and-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!