如何加密Java和解密在Android和iOS [英] How to encrypt in Java and decrypt in Android and iOS
问题描述
我有一个运行Java-jar文件的Linux服务器来加密几个文件。
I have a Linux server running a Java-jar file that encrypts several files.
Android和iPhone App下载该文件,并将其解密。我必须使用什么算法?
The Android and iPhone App download that file and shall decrypt it. What algorithm I have to use to do so?
我认识到我在Java中使用的算法在Android中不起作用。我在Java中做的是:
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?
推荐答案
iOS:
使用NSString + AESCrypt( https://github.com/Gurpartap/AESCrypt-ObjC )
I use NSString+AESCrypt (https://github.com/Gurpartap/AESCrypt-ObjC)
示例:
NSString* encrypted = [plainText AES256EncryptWithKey:@"MyEncryptionKey"];
NSString* decrypted = [encrypted AES256DecryptWithKey:@"MyEncryptionKey"];
Android(AES256Cipher - https://gist.github.com/dealforest/1949873 ):
Android (AES256Cipher - https://gist.github.com/dealforest/1949873):
加密:
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();
}
解密:
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();
}
这篇关于如何加密Java和解密在Android和iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!