I utilised TripleDES encryption in my Android app and it returns the expected string as required. However, when implementing the same feature in iOS using CommonCrypto, the returned string is different than what was expected.
public String encrypt(String message, String secretKey) throws Exception {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
KeySpec keySpec = new DESedeKeySpec(keyBytes);
SecretKey key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainTextBytes = message.getBytes("utf-8");
byte[] buf = cipher.doFinal(plainTextBytes);
byte[] base64Bytes = Base64.encodeBase64(buf);
String base64EncryptedString = new String(base64Bytes);
return base64EncryptedString;
}
iOS Code
+ (NSData*)transformData:(NSData*)inputData operation:(CCOperation)operation withPassword:(NSString*)password
{
NSData* key = [self keyFromPassword:password];
//NSData* iv = [self ivFromPassword:password];
NSMutableData* outputData = [NSMutableData dataWithLength:(inputData.length + kCCBlockSize3DES)];
size_t outLength;
CCCryptorStatus result = CCCrypt(operation, kCCAlgorithm3DES, kCCAlgorithmDES, key.bytes, key.length, nil, inputData.bytes, inputData.length, outputData.mutableBytes, outputData.length, &outLength);
if (result != kCCSuccess)
return nil;
[outputData setLength:outLength];
return outputData;
}
+ (NSData*)keyFromPassword:(NSString*)password
{
NSString* key = [password copy];
int length = kCCKeySize3DES;
while (key.length < length)
key = [key stringByAppendingString:password];
if (key.length > length)
key = [key substringToIndex:length];
return [key dataUsingEncoding:NSUTF8StringEncoding];
}
+ (NSData*)ivFromPassword:(NSString*)password
{
NSString* key = [password copy];
int length = 8;
while (key.length < length)
key = [key stringByAppendingString:password];
if (key.length > length)
key = [key substringToIndex:length];
return [key dataUsingEncoding:NSUTF8StringEncoding];
}
It may be helpful to note that the key being used is a 20 byte key. I am limited to the 20-byte key. The android app automatically takes care of this limitation with Array.copyOf function, however, despite zero padding and repeating the first characters of the key as the last eight characters, I still cannot replicate the output in iOS.
Any help will be appreciated.
Related
I tried to do AES encryption in Swift which I do in Android like this:
public static String Encrypt(String text, String key) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes = new byte[16];
byte[] b = key.getBytes("UTF-8");
int len = b.length;
if (len > keyBytes.length)
len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
return Base64.encodeToString(results, Base64.DEFAULT);
}
catch (Exception ex){return "error"+ex.getMessage();}
}
Below is the equivalent code in Swift 3.2:
func aesEncrypt(key: String, iv: String) throws -> String{
let data = self.data(using: String.Encoding.utf8)
let enc = try AES(key: key.bytes, blockMode: BlockMode.CBC(iv: iv.bytes, padding: Padding.pkcs5).encrypt(data!.bytes)
let encData = NSData(bytes: enc, length: Int(enc.count))
let base64String: String = encData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0));
let result = String(base64String)
return result!}
In Android it doesn't matter for key: I can fill with any string (no length limitations). But when using Swift I have to use a 32 charachter string for key and a 16 charachter string for IV, otherwise it will throw an error.
Here is the Swift usage:
let data = "this is string which I want to be encrypted"
let key = "bbbb98232-a343-4343f-2111"
let iv = "0000000000000000" // lenght = 16 like android code
let encryptedString = data.aesEncrypt(key: key, iv: iv);
Is there maybe some mistake in my Swift code?
You can try the below Swift code for AES encryption. Its String extension.
import Foundation
import CommonCrypto
extension String {
func aesEncrypt(key: String, initializationVector: String, options: Int = kCCOptionPKCS7Padding) -> String? {
if let keyData = key.data(using: String.Encoding.utf8),
let data = self.data(using: String.Encoding.utf8),
let cryptData = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(options)
var numBytesEncrypted: size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
(keyData as NSData).bytes, keyLength,
initializationVector,
(data as NSData).bytes, data.count,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
return base64cryptString
} else {
return nil
}
}
return nil
}
}
I have been trying to replicate an android code which does AES256 encryption using md5 doubled as the key. Everything seems to be fine but the values after the encryption doesn't seem to be the same. Please go through my below codes
Android :-
public static String encrypt(String key, String value) {
try {
byte[] keyArr = new byte[32];
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(key.getBytes("US-ASCII"));//in md5 function 1st line
keyArr = arrayCopy(0, hash, 0, keyArr, 16);//in md5 function 1st for loop
keyArr = arrayCopy(0, hash, 15, keyArr, 16);//in md5 function 2nd for loop
SecretKeySpec skeySpec = new SecretKeySpec(keyArr, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(value.getBytes());
String encryptedB64 = new String(Base64.encode(encrypted, Base64.DEFAULT));
return encryptedB64;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static byte[] arrayCopy(int sourceIndex,byte[] source,int targetIndex,byte[] target,int transferSize){
if(!(transferSize >0))
return null;
if(sourceIndex>=0 && sourceIndex < source.length){
int transferCnt=0;
int i=sourceIndex;
for(int j=targetIndex;;j++,i++){
if(targetIndex>=target.length || sourceIndex>=source.length || (++transferCnt>transferSize)){
break;
}
target[j] = source[i];
}
}else{
return null;
}
return target;
}
iOS objective-c
+ (NSString *) getFalconEncryptedValueForKey:(NSString *)theKey forString:(NSString *)theString
{
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
NSData *rawData = [theString dataUsingEncoding:NSUTF8StringEncoding];
NSString *md5Key = [self md5:theKey];
[md5Key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [rawData length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding + kCCOptionECBMode,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[rawData bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess)
{
NSData *tempData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
NSString* encrypted64 = [tempData base64EncodedStringWithOptions:0];//Even i have tried base 64 encding with other options available
return encrypted64;
}
free(buffer); //free the buffer;
return nil;
}
+ (NSString *) md5:(NSString *) input
{
// const char * pointer = [self UTF8String];
const char *cStr = [input cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
NSMutableString *md5String = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[md5String appendFormat:#"%02x",result[i]];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[md5String appendFormat:#"%02x",result[i]];
return md5String;
//for 32 byte. md5 produces only 16 byte info. we are replicating it again to make it 32 byte for aes256
}
Any kind of direction in what I have done wrong will be really helpful. Thanks in advance
AES256 encryption using md5 doubled as the key
No, that's not the case.
In Android, the last byte of the first hash in keyArr is overwritten by the second hash (more precisely the first byte of the second hash). Therefore, the last byte of keyArr is always 0.
I'm not fluent in Objective-C, but I think, this should do it:
NSMutableString *md5String = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH-1; i++)
[md5String appendFormat:#"%02x",result[i]];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[md5String appendFormat:#"%02x",result[i]];
[md5String appendFormat:#"%02x",0];
(Btw, arrayCopy can produce an IndexOutOfBoundsException despite its numerous checks).
Of course, this produces a Hex-encoded string with a length of 64 characters. This is not what you want. Instead, you should produce actual bytes of length 32.
Correct code (by OP)
+ (NSString *) getEncryptedValueWithKey:(NSString *)theKey forString:(NSString *)theString
{
NSData *rawData = [theString dataUsingEncoding:NSUTF8StringEncoding];
unsigned char md5Buffer[kCCKeySizeAES256+1];
memset(md5Buffer, 0, kCCKeySizeAES256+1);
const char *cStr = [theKey UTF8String];
// do md5 hashing
CC_MD5(cStr, CC_MD5_DIGEST_LENGTH, md5Buffer);
unsigned char lastChar = md5Buffer[15];
for (NSInteger i = 15; i <= 30; i++) {
md5Buffer[i] = md5Buffer[i-15];
}
md5Buffer[30] = lastChar;
//MD5 key obtaining end
NSUInteger dataLength = [rawData length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding + kCCOptionECBMode, md5Buffer, kCCKeySizeAES256, NULL /* initialization vector (optional) */, [rawData bytes], dataLength, /* input */ buffer, bufferSize, /* output */ &numBytesEncrypted);
if (cryptStatus == kCCSuccess)
{
NSData *tempData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
NSString* encrypted64 = [tempData base64EncodedStringWithOptions:0];//Even i have tried base 64 encding with other options available
return encrypted64;
}
free(buffer); //free the buffer;
return nil;
}
I am trying to generate ECDSA key pair using SpongyCastle in Android.
This is the code:
static {
Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
}
public static KeyPair generate() {
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("prime256v1");
KeyPairGenerator generator = KeyPairGenerator.getInstance("ECDSA", "SC");
generator.initialize(ecSpec, new SecureRandom());
KeyPair keyPair = g.generateKeyPair();
Log.i(TAG, "EC Pub Key generated: " + utils.bytesToHex(keyPair.getPublic().getEncoded()));
Log.i(TAG, "EC Private Key generated: " + utils.bytesToHex(keyPair.getPrivate().getEncoded()));
return generator.generateKeyPair();
}
Something is wrong since I always get something like that example of
Public Key:
3059301306072A8648CE3D020106082A8648CE3D03010703420004483ABA9F322240010ECF00E818C041A60FE71A2BD64C64CD5A60519985F110AEDE6308027D2730303F5E2478F083C7F5BB683DCAC22BFEB62F3A48BD01009F40
and Private Key:
308193020100301306072A8648CE3D020106082A8648CE3D030107047930770201010420219AB4B3701630973A4B2917D53F69A4BE6DAD61F48016BFEF147B2999575CB2A00A06082A8648CE3D030107A14403420004483ABA9F322240010ECF00E818C041A60FE71A2BD64C64CD5A60519985F110AEDE6308027D2730303F5E2478F083C7F5BB683DCAC22BFEB62F3A48BD01009F40
The site ECDSA sample give Invalid ECDSA signature, and them seems really very different from that smaller Private Key and always starting with "04" Public Key generated in the same site.
Also, my backend verification gives me the error "Invalid point encoding 0x30"
The backend Java method check is:
public ECPublicKey getPublicKeyFromHex(String publicKeyHex)
throws NoSuchAlgorithmException, DecoderException, ApplicationGenericException {
byte[] rawPublicKey = Hex.decodeHex(publicKeyHex.toCharArray());
ECPublicKey ecPublicKey = null;
KeyFactory kf = null;
ECNamedCurveParameterSpec ecNamedCurveParameterSpec = ECNamedCurveTable.getParameterSpec("prime256v1");
ECCurve curve = ecNamedCurveParameterSpec.getCurve();
EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, ecNamedCurveParameterSpec.getSeed());
java.security.spec.ECPoint ecPoint = ECPointUtil.decodePoint(ellipticCurve, rawPublicKey);
java.security.spec.ECParameterSpec ecParameterSpec = EC5Util.convertSpec(ellipticCurve,
ecNamedCurveParameterSpec);
java.security.spec.ECPublicKeySpec publicKeySpec = new java.security.spec.ECPublicKeySpec(ecPoint,
ecParameterSpec);
kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
try {
ecPublicKey = (ECPublicKey) kf.generatePublic(publicKeySpec);
} catch (Exception e) {
throw new ApplicationGenericException(e.getMessage(), e.getCause());
}
return ecPublicKey;
}
Convert generated public key to decoded bytes array or hex string:
public String getPublicKeyAsHex(PublicKey publicKey){
ECPublicKey ecPublicKey = (ECPublicKey)publicKey;
ECPoint ecPoint = ecPublicKey.getW();
byte[] publicKeyBytes = new byte[PUBLIC_KEY_LENGTH];
writeToStream(publicKeyBytes, 0, ecPoint.getAffineX(), PRIVATE_KEY_LENGTH);
writeToStream(publicKeyBytes, PRIVATE_KEY_LENGTH, ecPoint.getAffineY(), PRIVATE_KEY_LENGTH);
String hex = Hex.toHexString(publicKeyBytes);
logger.debug("Public key bytes: " + Arrays.toString(publicKeyBytes));
logger.debug("Public key hex: " + hex);
return hex;
}
private void writeToStream(byte[] stream, int start, BigInteger value, int size) {
byte[] data = value.toByteArray();
int length = Math.min(size, data.length);
int writeStart = start + size - length;
int readStart = data.length - length;
System.arraycopy(data, readStart, stream, writeStart, length);
}
Convert decoded bytes array back to PublicKey:
KeyFactory factory = KeyFactory.getInstance(ALGORITHM, ALGORITHM_PROVIDER);
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(CURVE);
ECNamedCurveSpec params = new ECNamedCurveSpec(CURVE, spec.getCurve(), spec.getG(), spec.getN());
BigInteger xCoordinate = new BigInteger(1, Arrays.copyOfRange(decodedPublicKey, 0, PRIVATE_KEY_LENGTH));
BigInteger yCoordinate = new BigInteger(1, Arrays.copyOfRange(decodedPublicKey, PRIVATE_KEY_LENGTH, PUBLIC_KEY_LENGTH));
java.security.spec.ECPoint w = new java.security.spec.ECPoint(xCoordinate, yCoordinate);
PublicKey encodedPublicKey = factory.generatePublic(new java.security.spec.ECPublicKeySpec(w, params));
I'm trying do some encrypt something using 3des on the iOS that must match the results from java and .NET.
Java code is :
public class EncryptionHelper {
// Encrypts string and encode in Base64
public static String encryptText(String plainText,String key, String IV) throws Exception {
// ---- Use specified 3DES key and IV from other source --------------
byte[] plaintext = plainText.getBytes();//input
byte[] tdesKeyData = key.getBytes();// your encryption key
byte[] myIV = IV.getBytes();// initialization vector
Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(myIV);
c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
byte[] cipherText = c3des.doFinal(plaintext);
String encryptedString = Base64.encodeToString(cipherText,
Base64.DEFAULT);
// return Base64Coder.encodeString(new String(cipherText));
return encryptedString;
}
}
and iOS code for the same is :
-(NSString*)new3DESwithoperand:(NSString*)plaintext encryptOrDecrypt:(CCOperation)encryptorDecrypt key:(NSString*)key initVec:(NSString*)initVec
{
NSData* data = [plaintext dataUsingEncoding:NSUTF8StringEncoding];
const void *vplainText = [data bytes];;
size_t plainTextBufferSize = [data length];
NSLog(#"%#, Length: %u",[data description],[data length]);
size_t bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
NSLog(#"%zu, sizof of uint8_t: %zu",bufferPtrSize, sizeof(uint8_t));
size_t movedBytes = 0;
uint8_t *bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
NSLog(#"%zu",sizeof(bufferPtr));
memset((void*)bufferPtr, 0x0, bufferPtrSize);
NSLog(#"%zu",sizeof(bufferPtr));
const void * vkey = [[NSData base64DataFromString:key] bytes];
const void *vinitVec = [[NSData base64DataFromString:initVec] bytes];
NSLog(#"vinitvec: %#",[[NSData base64DataFromString:initVec] description]);
CCCryptorStatus ccStatus;
ccStatus = CCCrypt(encryptorDecrypt,
kCCAlgorithm3DES,
kCCOptionPKCS7Padding & kCCModeCBC,
vkey,
kCCKeySize3DES,
vinitVec,
vplainText,
plainTextBufferSize,
(void*)bufferPtr,
bufferPtrSize,
&movedBytes);
NSData* result = [NSData dataWithBytes:(const void*)bufferPtr length:(NSUInteger)movedBytes];
NSString* str = [NSString base64StringFromData:result length:result.length];
NSLog(#"%#",str);
return str;
}
This code successfully encrypts and decrypts a string. However, it does not match the results from .NET and java.
Thank you
Have found a solution for the above problem of encryption value generated different on iOS and .NET or Java.
Solution:
1. In Android and .NET you have to use a key of size 16 Bytes (eg: key="1234567890123456")
In iOS you need to use a key size of 24 bytes but the generation of key makes a little difference.
Use the same key as used in Android or .NET (16 bytes) and append it with the first 8 Bytes of the same key.
key16Byte = "1234567890123456" //Android and .NET key
key24Byte = key16Byte + "12345678" //ios and Java key, Replicated first 8 Bytes of 16Byte key
//new24ByteKey = "123456789012345612345678"
Remove "& kCCModeCBC" from CCypher Mode.
Some values require bytes in CCCrypt function which I have changed in the below mentioned code below. like keyData, encryptData.
Reason for different encryption generated:
Android and .NET - It takes 16Byte key and internally replicates, and generates a 24Byte key.
Java - It throws an Exception "Invalid key length", if you provide a 16Byte key value.
iOS - It generates encryption value with 16Byte and 24Byte both values without throwing any exception, so is the reason we get a different encryption generated in case of 16Byte key.
Java Code
public class EncryptionHelper {
// Encrypts string and encode in Base64
public static String encryptText(String plainText,String key, String IV) throws Exception {
// ---- Use specified 3DES key and IV from other source --------------
byte[] plaintext = plainText.getBytes();//input
byte[] tdesKeyData = key.getBytes();// your encryption key
byte[] myIV = IV.getBytes();// initialization vector
Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(myIV);
c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
byte[] cipherText = c3des.doFinal(plaintext);
String encryptedString = Base64.encodeToString(cipherText,
Base64.DEFAULT);
// return Base64Coder.encodeString(new String(cipherText));
return encryptedString;
}
iOS Code:
- (NSString *)encrypt:(NSString *)encryptValue key:(NSString *)key24Byte IV:(NSString *)IV{
// first of all we need to prepare key
if([key length] != 24)
return #"Require 24 byte key, call function generate24ByteKeySameAsAndroidDotNet with a 16Byte key same as used in Android and .NET"; //temporary error message
NSData *keyData = [key24Byte dataUsingEncoding:NSUTF8StringEncoding];
// our key is ready, let's prepare other buffers and moved bytes length
NSData *encryptData = [encryptValue dataUsingEncoding:NSUTF8StringEncoding];
size_t resultBufferSize = [encryptData length] + kCCBlockSize3DES;
unsigned char resultBuffer[resultBufferSize];
size_t moved = 0;
// DES-CBC requires an explicit Initialization Vector (IV)
// IV - second half of md5 key
NSMutableData *ivData = [[IV dataUsingEncoding:NSUTF8StringEncoding]mutableCopy];
NSMutableData *iv = [NSMutableData dataWithData:ivData];
CCCryptorStatus cryptorStatus = CCCrypt(kCCEncrypt, kCCAlgorithm3DES,
kCCOptionPKCS7Padding , [keyData bytes],
kCCKeySize3DES, [iv bytes],
[encryptData bytes], [encryptData length],
resultBuffer, resultBufferSize, &moved);
if (cryptorStatus == kCCSuccess) {
return [[NSData dataWithBytes:resultBuffer length:moved] base64EncodedStringWithOptions:0];
} else {
return nil;
}
}
iOS
-(NSString *)generate24ByteKeySameAsAndroidDotNet:(NSString *)key{
NSString *new24ByteKey = key;
;
new24ByteKey = [new24ByteKey stringByAppendingString:[key substringWithRange:NSMakeRange(0, 8)]];
return new24ByteKey;
}
As #Jugal Desai mentioned, the key difference between iOS and Android/.Net is that the later ones automatically fill the key (with size 16 bytes) with another 8 bytes from the start of the key! You saved me :)
Here I provide the simple fix in Swift 3:
....
YOUR_KEY_SIZE_16 = YOUR_KEY_SIZE_16 + YOUR_KEY_SIZE_16[0...7]
....
Sample complete code (MD5 for key hash + ECB + PKCS7Padding) with base64 result:
func tripleDesEncrypt(keyString: String, pass: String) -> String{
let keyData = keyString.data(using: .utf8)!
var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))
_ = digestData.withUnsafeMutableBytes {digestBytes in
keyData.withUnsafeBytes {messageBytes in
CC_MD5(messageBytes, CC_LONG(keyData.count), digestBytes)
}
}
digestData = digestData + digestData[0...7]
let data = pass.data(using: .utf8)!
let dataNS = data as NSData
let cryptData = NSMutableData(length: Int(dataNS.length) + kCCBlockSize3DES)!
let keyLength = size_t(kCCKeySize3DES)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithm3DES)
let options: CCOptions = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
(digestData as NSData).bytes,
keyLength,
nil,
dataNS.bytes,
dataNS.length,
cryptData.mutableBytes,
cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
// Not all data is a UTF-8 string so Base64 is used
let base64cryptString = cryptData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength76Characters)
return base64cryptString
} else {
print("Error: \(cryptStatus)")
}
return ""
}
How serious in decrypted?
- (NSString *)encrypt:(NSString *)encryptValue key:(NSString *)key24Byte IV:(NSString *)IV{
// first of all we need to prepare key
if([key length] != 24)
return #"Require 24 byte key, call function generate24ByteKeySameAsAndroidDotNet with a 16Byte key same as used in Android and .NET"; //temporary error message
NSData *keyData = [key24Byte dataUsingEncoding:NSUTF8StringEncoding];
// our key is ready, let's prepare other buffers and moved bytes length
NSData *encryptData = [encryptValue dataUsingEncoding:NSUTF8StringEncoding];
size_t resultBufferSize = [encryptData length] + kCCBlockSize3DES;
unsigned char resultBuffer[resultBufferSize];
size_t moved = 0;
// DES-CBC requires an explicit Initialization Vector (IV)
// IV - second half of md5 key
NSMutableData *ivData = [[IV dataUsingEncoding:NSUTF8StringEncoding]mutableCopy];
NSMutableData *iv = [NSMutableData dataWithData:ivData];
CCCryptorStatus cryptorStatus = CCCrypt(kCCEncrypt, kCCAlgorithm3DES,
kCCOptionPKCS7Padding , [keyData bytes],
kCCKeySize3DES, [iv bytes],
[encryptData bytes], [encryptData length],
resultBuffer, resultBufferSize, &moved);
if (cryptorStatus == kCCSuccess) {
return [[NSData dataWithBytes:resultBuffer length:moved] base64EncodedStringWithOptions:0];
} else {
return nil;
}
}
I have to do the following operation:
Encryption VB -> Decryption VB
Encryption Android - Decryption Android
Encryption VB -> Decryption Android
Encryption Android -> decryption VB
So far I succedded do encrypt and decrypt on Android.
When I encrypt in VB and try to decrypt on Android, I get the following exception:
E/Exception: pad block corrupted
I also have to mention that when i encrypt short strings in VB and decrypt them also in VB, everything works well. But when i encrypt a larger array of bytes, the decryption works but the result is not the one expected.
Can somebody give me a hint of how to solve the problem?
Thank you !
Here is my code:
.NET functions
Public Function AES_Encrypt2(ByVal byteArray() As Byte, ByVal key As String, Optional ByVal ShortKey As Boolean = False) As String
Try
Dim FirstKeyBytes() As Byte = Encoding.UTF8.GetBytes(key)
If Not FirstKeyBytes Is Nothing Then
If FirstKeyBytes.Length < 32 Then
Array.Resize(FirstKeyBytes, 32)
End If
End If
Dim KeyBytes() As Byte
If ShortKey Then
KeyBytes = New Byte(15) {}
Array.Copy(FirstKeyBytes, KeyBytes, 16)
Else
KeyBytes = New Byte(31) {}
Array.Copy(FirstKeyBytes, KeyBytes, 32)
End If
Dim InitialVectorBytes() As Byte = New Byte() {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 'Encoding.UTF8.GetBytes("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
Dim SymmetricKey As New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
SymmetricKey.Padding = PaddingMode.PKCS7
Dim Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)
Dim MemStream As New MemoryStream()
Dim CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)
CryptoStream.Write(byteArray, 0, byteArray.Length)
CryptoStream.FlushFinalBlock()
MemStream.Close()
CryptoStream.Close()
Dim CipherTextBytes As Byte() = MemStream.ToArray()
Dim encryptedString As String = Convert.ToBase64String(CipherTextBytes)
Return encryptedString
Catch ex As Exception
Return String.Empty
End Try
End Function
Public Function AES_Decrypt2(ByVal encryptedString As String, ByVal key As String, Optional ByVal ShortKey As Boolean = False) As String
Try
Dim PlainTextBytes1 As Byte() = Convert.FromBase64String(encryptedString)
Dim FirstKeyBytes() As Byte = Encoding.UTF8.GetBytes(key)
If Not FirstKeyBytes Is Nothing Then
If FirstKeyBytes.Length < 32 Then
Array.Resize(FirstKeyBytes, 32)
End If
End If
Dim KeyBytes() As Byte
If ShortKey Then
KeyBytes = New Byte(15) {}
Array.Copy(FirstKeyBytes, KeyBytes, 16)
Else
KeyBytes = New Byte(31) {}
Array.Copy(FirstKeyBytes, KeyBytes, 32)
End If
Dim SymmetricKey As New RijndaelManaged()
Dim InitialVectorBytes As Byte() = New Byte() {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 'Encoding.UTF8.GetBytes("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
SymmetricKey.Mode = CipherMode.CBC
SymmetricKey.Padding = PaddingMode.PKCS7
Dim Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)
Dim MemStream1 As New MemoryStream(PlainTextBytes1)
Dim CryptoStream As New CryptoStream(MemStream1, Decryptor, CryptoStreamMode.Read)
Dim pltxt As Byte() = New Byte(PlainTextBytes1.Length - 1) {}
Dim d As Integer = CryptoStream.Read(pltxt, 0, pltxt.Length)
MemStream1.Close()
CryptoStream.Close()
Dim textConverter As New ASCIIEncoding()
Dim round As String = textConverter.GetString(pltxt, 0, d)
Return round
Catch ex As Exception
Return String.Empty
End Try
End Function
And Android methods:
public static String encrypt(byte[] input, String key) {
try {
byte[] iv = new byte[16];
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
String newKey = "";
if (key.length() >= 32) {
newKey = key.substring(0, 32);
} else {
for (int i = key.length(); i < 32; i++) {
key += "0";
}
newKey = key.substring(0, 32);
}
SecretKeySpec skeySpec = new SecretKeySpec(newKey.getBytes(), "AES");
//skeySpec = new SecretKeySpec(newKey.getBytes(), 0, newKey.length(), "AES");
Cipher fileCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
fileCipher.init(1, skeySpec, paramSpec);
byte[] decrypted = fileCipher.doFinal(input);
byte[] base64enc = Base64.encode(decrypted, 0);
return new String(base64enc);
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return null;
}
public static byte[] decrypt(String input, String key) {
try {
byte[] iv = new byte[16];
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
byte[] base64enc = Base64.decode(input.getBytes(), 0);
String newKey = "";
if (key.length() >= 32) {
newKey = key.substring(0, 32);
} else {
for (int i = key.length(); i < 32; i++) {
key += "0";
}
newKey = key.substring(0, 32);;
}
SecretKeySpec skeySpec = new SecretKeySpec(newKey.getBytes(), "AES");
Cipher fileCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
fileCipher.init(2, skeySpec, paramSpec);
int x = base64enc.length;
return fileCipher.doFinal(base64enc);
} catch (Exception e) {
Log.e("Exception: ", e.getMessage());
}
return null;
}
I guess the main issue is that the key generation is different in both pieces of code. Passwords are not keys, you should use either binary, randomly generated keys or a good key derivation mechanism like PBKDF2.
Trying to find a well vetted lib. that does use the same protocol for encryption in .NET and Java (/Android) would also be a good idea.
In general, input to cryptographic algorithms need to be binary. Always compare all inputs of your algorithms using hexadecimal encoding right before executing the algorithm.