AES -128 Encrypted secret Key from JAVA decrypt in Swift

I have AES encrypted secret key that i have to decrypt in Swift.

Which giving me error when doing like this

let EncryptedSecretKey = "bjgZTpZD7DvrjTRXJ6LCA9GpkDnLJLgIVAmFWFXNUVqVWdjXOiOGeRHJx8owW6Pp/a5ECe8CljlwZIAFhRUEPfTks22yntUOhrCUbDzzqYOMiQYfEV/h7/zahl4PV1t4rHXDsQPaf7Rrl8k5jKj0Cf7E aKA4U/pyAjZlvVhMjH8="

let decodedData = Data(base64Encoded: EncryptedSecretKey)! crashing in this Line

  let decodedString = String(data: decodedData, encoding: .utf8)!

let mySecretKeyDecrypt = decrypt(decodedData, withKey: b64Key)

Using this method to decrypt the key

func decrypt( data: Data?, withKey key: String?) -> String? {

        return String(data: aesOperation(CCOperation(kCCDecrypt), on: data, key: key)!, encoding: .utf8)

    }

    func aesOperation(
operation: CCOperation, on data: Data?, key: String?) -> Data? {

        var keyPtr = [Int8]()

        bzero(&keyPtr, MemoryLayout.size(ofValue: keyPtr))

        key?.getCString(&keyPtr, maxLength: MemoryLayout.size(ofValue: keyPtr), encoding: .utf8)

        let dataLength = data?.count ?? 0

        let bufferSize = dataLength + kCCBlockSizeAES128

        var buffer = malloc(bufferSize)
        var numBytesEncrypted: size_t = 0

        let cryptStatus = CCCrypt(operation, CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), keyPtr, kCCBlockSizeAES128, keyPtr, data?.bytes, dataLength, buffer, bufferSize, &numBytesEncrypted)

        if cryptStatus == kCCSuccess {

            print("Success")

            return Data(bytes: &buffer, count: numBytesEncrypted)

        }
free(buffer)

        return nil

    }
Your EncryptedSecretKey has an extra whitespace before aKA4U/pyAjZlvVhMjH8=.
You may need to remove it,
or make Data.init to ignore it.
Code Block
let decodedData = Data(base64Encoded: EncryptedSecretKey, options: .ignoreUnknownCharacters)!


But the next line is meaningless, you should remove it.
Code Block
let decodedString = String(data: decodedData, encoding: .utf8)!

It is very unlikely that you can decode an encrypted binary data as UTF-8 String.
The line will always cause your app crash. (Generally you use too many forced-unwrappings ! in your code.)


I really doubt your aesOperation is treating the key b64Key properly.
But your question in post is about crashing in this Line, you should start another thread for another question, with including enough info.


One more, please use the code insertion feature (shown with icon < >) properly.
Thanks  OOPer  for your Reply.I got the Space issue and corrected that.
But the concern is how to move further with decrypting the encrypted secret key from JAVA . i.e.
bjgZTpZD7DvrjTRXJ6LCA9GpkDnLJLgIVAmFWFXNUVqVWdjXOiOGeRHJx8owW6Pp/a5ECe8CljlwZIAFhRUEPfTks22yntUOhrCUbDzzqYOMiQYfEV/h7/zahl4PV1t4rHXDsQPaf7Rrl8k5jKj0Cf7EaKA4U/pyAjZlvVhMjH8=

I need to use SecKeyCreateWithData method to create seckey and then decrypt..
Or use any AES decrypting library as want to decrypt secret key from private key.

As have used CryptoSwift method to decrypt the secret key but giving me error "Invalid Key size"
Code Block
static func decryptArtisan(cryptedMessage: String , key:String) -> String? {
        var clairMessage:String? = nil;
        if let cryptedData = Data(base64Encoded: cryptedMessage) {
            do {
                let aes = try CryptoSwift.AES(key: Array<UInt8>(key.utf8), blockMode: ECB(), padding: .noPadding)
                let cipher = try aes.decrypt(Array<UInt8>(cryptedData))
                clairMessage = String(bytes: cipher, encoding: .utf8)
            }catch{
                print(error)
            }
        }
        return clairMessage
    }



Not able to understand this. Please help
Sorry, but I have never used CryptoSwift to encrypt/decrypt something in Swift.

But the concern is how to move further with decrypting the encrypted secret key from JAVA 

It is not written in the original post of this thread. You have asked about crashing in this Line and it is solved, no?

You should go step by step. I believe your right direction is checking if you have gotten the right private key from Private Key in another thread of yours.

I got privKey of type SecKey from your Private Key, and when I printed it with:
Code Block
print("privKey:", privKey)

Output was:
Code Block
privKey: <SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, block size: 1024 bits, addr: 0x10300a6e0>


Thanks OOPer , I could resave my issue of crash as you pointed out the issue correctly.
I am too doing encryption for the first time and I could not find enough support from online as In my situation I have the encrypted secret key from java and i have to decrypt at my end in Swift.
So looking for support in this case.

The java code for generation of secret key is
Code Block
public class ClientEncrypt {
// private static String publicKeyString = "<your_public_key_here>";
// private static String publicKeyString = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJwdPPeUl9Jknt6gcB98xcsUGlp1ISopEfHL4WFPvYB04UKf9aJOzUpAynl0ZNgI2wBejL6+Ap6pGkqmn2AamEdg24G0G8u//0nDIQYdtDpwoxmADEG2UaEz4+DxFTjH2JICD2WQRx2bjd3h6GN/BimJRVYhs8CLtvhr0f6iJZ9VAgMBAAECgYAu8sgL+L7zwdjZQMyXW5GsMf5+56yynilMWzELb8ygngXEYJChYCtywith/TP6mCcsZELVdhUZm+dRPey+HSFgFa3XDQV+IQZG2f3RK/L78cUFnzXjIwa8INHI7dkfZVBBW6fY1pdzjcEVl0lVAkeLvMowb00wMMlrFSVGnFBBYQJBAMg3anp33/GxuUTV8al6UwEVYwXuOCV5R+vc1M0MW4fEXceFX+GUPL4yF/k6h/AT/Qx90jS6BpUs4OfE1L4/KGkCQQDHnDJptJwp5WTzZLErUSSKBotWar7uo+kCpDer8BCrBZUqqff8f8B3rCGohwrvLJkY1H0I/2VuV4pYGuIXqcINAkBAu5IEmJ9iIIj7FYT1u6P8lLKYZ0Xl78luG879oMIzKiz75kZyw5/ECqQvo1nyKDRHhqKhA4g/UOxCYyQ5gmgJAkAeYzgFgZpYgnSY3RZfqs2uOYrS0BNbDxb08P0MrtJKxuHLie6XwPcTAOBq4IwYlyiDcC3MxdyyLJ+CBC2xPoWtAkAOB7PvjFeFcL5JZe/MpM0NW+CkKOAu8Xs4L9qihnMlZE6zZDwbbDFONyxJeDlcRmGlvlCPPxL1blZGgVeQW/M1";
private static String publicKeyString = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDFzfAPe5h40OHut+gT5JEm5MEqw4SVbsWKdusLXPawqBNPPn6TpWhbHgFJfe3HsqpmpdXBslSWM7T/8Pu9+XzKiPoGTzG91a59kl2kMYNQE0GeIJmzHrqPSiw3QG64fU10mzR/Ys9Yh2FyTcbaekDSUqkL7KpDTPV35eAWs6vHmQIDAQAB";
public static void main(String args[]) {
try {
// 1. generate secret key using AES
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128); // AES is currently available in three key sizes: 128, 192 and 256 bits.The
// design and strength of all key lengths of the AES algorithm are sufficient to
// protect classified information up to the SECRET level
SecretKey secretKey = keyGenerator.generateKey();
// 2. get string which needs to be encrypted
String text = "<your_string_which_needs_to_be_encrypted_here>";
// 3. encrypt string using secret key
byte[] raw = secretKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
String cipherTextString = Base64.encodeToString(cipher.doFinal(text.getBytes(Charset.forName("UTF-8"))),
Base64.DEFAULT);
System.out.println("cipherTextString : "+cipherTextString);
// 4. get public key
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(publicKeyString, Base64.DEFAULT));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(publicSpec);
// 6. encrypt secret key using public key
Cipher cipher2 = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher2.init(Cipher.ENCRYPT_MODE, publicKey);
String encryptedSecretKey = Base64.encodeToString(cipher2.doFinal(secretKey.getEncoded()), Base64.DEFAULT);
//System.out.println(encryptedSecretKey);
System.out.println("encryptedSecretKey : "+encryptedSecretKey);
// 7. pass cipherTextString (encypted sensitive data) and encryptedSecretKey to
// your server via your preferred way.
// Tips:
// You may use JSON to combine both the strings under 1 object.
// You may use a volley call to send this data to your server.
} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException
| BadPaddingException | InvalidKeySpecException | InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
}
}

I have been able to get the Sec private key at my end , but not able decrypt the secret key encrypted in AES-128 in java that i mentioned above also to move further I need this secret key decrypted to decrypt my message successfully.
bjgZTpZD7DvrjTRXJ6LCA9GpkDnLJLgIVAmFWFXNUVqVWdjXOiOGeRHJx8owW6Pp/a5ECe8CljlwZIAFhRUEPfTks22yntUOhrCUbDzzqYOMiQYfEV/h7/zahl4PV1t4rHXDsQPaf7Rrl8k5jKj0Cf7EaKA4U/pyAjZlvVhMjH8=

Thanks in advance for any help in this regard.!!!

I am really disappointed that you do not hear my words.
Please do not ask two different things in one thread. You should start a new thread if you want to ask other things than the one in the opening post.

Please include enough info about your SekKey into the new thread.

I have been able to get the Sec private key at my end

How have you checked that is the right one?
(Pease do not reply in this thread, write everything needed in the new thread.)
OK..Thanks OOPer
I have opened a new thread OOPer  if you can check that .. Thanks!!
AES -128 Encrypted secret Key from JAVA decrypt in Swift
 
 
Q