У меня есть класс Java, который шифрует строку и затем преобразует ее в Base64, который используется в приложении для Android: (этот код использовался из этого примера (обратите внимание на пробелы в гиперссылке): http://stackoverflow. com/questions/2090765/encryption-compatibleable-between-android-and-c)
public class encryption {
public static final String TAG = "smsfwd"
private static Cipher aesCipher;
private static SecretKey secretKey;
private static IvParameterSpec ivParameterSpec;
private static String CIPHER_TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static String CIPHER_ALGORITHM = "AES";
//the secret key in HEX is 'secretkey'
private static byte[] rawSecretKey = {Ox73, Ox65, Ox63, Ox72, Ox65, Ox74, Ox6B, Ox65, Ox79};
private static String MESSAGEDIGEST_ALGORITHM = "MD5";
public encryption(String passphrase) {
byte[] passwordKey = encodeDigest(passphrase);
try {
aesCipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "No such algorithm " + CIPHER_ALGORITHM, e);
} catch (NoSuchPaddingException e) {
Log.e(TAG, "No such padding PKCS5", e);
}
secretKey = new SecretKeySpec(passwordKey, CIPHER_ALGORITHM);
ivParameterSpec = new IvParameterSpec(rawSecretKey);
}
//base 64 encryption
public String encryptAsBase64(byte[] clearData) {
byte[] encryptedData = encrypt(clearData);
return base64.encodeBytes(encryptedData);
}
public byte[] encrypt(byte[] clearData) {
try {
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key", e);
return null;
} catch (InvalidAlgorithmParameterException e) {
Log.e(TAG, "Invalid algorithm " + CIPHER_ALGORITHM, e);
return null;
}
byte[] encryptedData;
try {
encryptedData = aesCipher.doFinal(clearData);
} catch (IllegalBlockSizeException e) {
Log.e(TAG, "Illegal block size", e);
return null;
} catch (BadPaddingException e) {
Log.e(TAG, "Bad padding", e);
return null;
}
return encryptedData;
}
private byte[] encodeDigest(String text) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance(MESSAGEDIGEST_ALGORITHM);
return digest.digest(text.getBytes());
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "No such algorithm " + MESSAGEDIGEST_ALGORITHM, e);
}
return null;
}
}
И начинается шифрование базы 64 (обратите внимание на пробелы в гиперссылке) http://iharder.sourceforge.net/current/java/base64/
Что происходит, так это то, что он передается на сервер С#/.NET для дешифрования, и все отлично работает на Android. Теперь проблема конвертируется в Objective-C для использования на iPhone.
Я провел много исследований, и самый близкий ответ - http://dotmac.rationalmind.net/2009/02/aes-interoperability-between-net-and-iphone/
Однако, когда я использую этот пример (код, взятый прямо из загруженного zip файла), я получаю "Заполнение недействительным и не может быть удалено". стороне сервера ошибок.
Мой код на стороне сервера:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
namespace test.Business
{
public class Crypto
{
private ICryptoTransform rijndaelDecryptor;
// Replace me with a 16-byte key, share between Java and C#
private static byte[] rawSecretKey = {Ox73, Ox65, Ox63, Ox72, Ox65, Ox74, Ox6B, Ox65, Ox79};
public Crypto(string passphrase, bool encrypt)
{
byte[] passwordKey = encodeDigest(passphrase);
RijndaelManaged rijndael = new RijndaelManaged();
if(encrypt)
rijndaelDecryptor = rijndael.CreateEncryptor(passwordKey, rawSecretKey);
else
rijndaelDecryptor = rijndael.CreateDecryptor(passwordKey, rawSecretKey);
}
public Crypto(string passphrase)
{
byte[] passwordKey = encodeDigest(passphrase);
RijndaelManaged rijndael = new RijndaelManaged();
rijndaelDecryptor = rijndael.CreateDecryptor(passwordKey, rawSecretKey);
}
private string Decrypt(byte[] encryptedData)
{
byte[] newClearData;
try
{
newClearData = rijndaelDecryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
}
catch
{
throw;
}
return Encoding.ASCII.GetString(newClearData);
}
internal string DecyptString(string token)
{
//UTF8Encoding utf8 = new UTF8Encoding();
return Decrypt(ASCIIEncoding.ASCII.GetBytes(token));
}
internal string DecryptFromBase64(string encryptedBase64)
{
return Decrypt(Convert.FromBase64String(encryptedBase64));
}
private byte[] encodeDigest(string text)
{
MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] data = Encoding.ASCII.GetBytes(text);
return x.ComputeHash(data);
}
//Encryption Code
public string EncryptAsBase64(string strData)
{
byte[] clearData = Encoding.ASCII.GetBytes(strData);
byte[] encryptedData = Encrypt(clearData);
return Convert.ToBase64String(encryptedData);
}
public byte[] Encrypt(byte[] clearData)
{
byte[] test1 = new byte[clearData.Length];
try
{
test1 = rijndaelDecryptor.TransformFinalBlock(clearData, 0, clearData.Length);
}
catch
{
throw;
}
return test1;
}
}
}
Любые идеи? Спасибо вам очень заблаговременно!
Вы можете получить категорию NSData для обработки кодировки/декодирования Base64 здесь:
http://cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
Здесь вы можете найти библиотеку и категорию NSData для шифрования AES:
http://iphonedevelopment.blogspot.com/2009/02/strong-encryption-for-cocoa-cocoa-touch.html
Между двумя, вы можете реплицировать то, что вы делаете, и, вероятно, с меньшим количеством кода...