C#で
void test(){
string ctB64 = encrypt("hola");
Console.WriteLine(ctB64); // the same as in objective-c
}
string encrypt(string input)
{
try
{
// Create a new instance of the AesManaged class. This generates a new key and initialization vector (IV).
AesManaged myAes = new AesManaged();
// Override the cipher mode, key and IV
myAes.Mode = CipherMode.CBC;
myAes.IV = new byte[16] { 0x10, 0x16, 0x1F, 0xAD, 0x10, 0x10, 0xAA, 0x22, 0x12, 0x51, 0xF1, 0x1E, 0x15, 0x11, 0x1B, 0x10 }; // must be the same as in objective-c
myAes.Key = Encoding.UTF8.GetBytes(“0123456789123456”);
//CipherKey; // Byte array representing the key
myAes.Padding = PaddingMode.PKCS7;
// Create a encryption object to perform the stream transform.
ICryptoTransform encryptor = myAes.CreateEncryptor();
// perform the encryption as required...
MemoryStream ms = new MemoryStream();
CryptoStream ct = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
byte[] binput = Encoding.UTF8.GetBytes(input);
ct.Write(binput, 0, binput.Length);
ct.Close();
byte [] result = ms.ToArray();
return Convert.ToBase64String(result);
}
catch (Exception ex)
{
// TODO: Log the error
Console.WriteLine(ex);
throw ex;
}
}
· Objective-c で、 https: //github.com/kelp404/CocoaSecurity から CocoaSecurity ライブラリを追加します。
#import "CocoaSecurity.h"
#import "Base64.h"
…
- (void) test{
unsigned char bytes[] = { 0x10, 0x16, 0x1F, 0xAD, 0x10, 0x10, 0xAA, 0x22, 0x12, 0x51, 0xF1, 0x1E, 0x15, 0x11, 0x1B, 0x10 }; // must be the same as in c#
NSData *iv = [NSData dataWithBytesNoCopy:bytes length:16 freeWhenDone:YES];
NSData* key = [@"0123456789123456" dataUsingEncoding:NSUTF8StringEncoding];
CocoaSecurityResult *result = [CocoaSecurity aesEncrypt:@"hola" key:key iv:iv];
NSLog(@"%@", result.base64); // the same as in c#
NSData *data = [NSData dataWithBase64EncodedString:result.base64];
CocoaSecurityResult *result2 = [CocoaSecurity aesDecryptWithData:data key:key iv:iv];
NSLog(@"%@", result2.utf8String); // show "hola"
}