如何在Java加密和解密在Android和iOS如何在、Java、iOS、Android

由网友(清溪落月诗如洗)分享简介:我有一个Linux服务器上运行的加密多个文件一个Java-jar文件。I have a Linux server running a Java-jar file that encrypts several files.在Android和iPhone应用程序下载该文件,并应进行解密。我一定要使用的话哪种算法?The...

我有一个Linux服务器上运行的加密多个文件一个Java-jar文件。

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

在Android和iPhone应用程序下载该文件,并应进行解密。我一定要使用的话哪种算法?

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;
}

什么也没有超过code工作? 任何替代方案?

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"];

安卓(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();
}
阅读全文

相关推荐

最新文章