Skip to content

How to decrypt code in Crypto Swift which is encrypted by default config of CryptoJS #513

@nirmal-opencrowd

Description

@nirmal-opencrowd

I'm trying to decrypt a string which is encrypted by CryptoJS AES encryption in Swift but I don't know if I'm using the right configuration to decrypt it.

This function used for encrypting the message

var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");

Here is code, which I'm using in swift

import Foundation
import CryptoSwift

static func decryptAES256CryptoJS(encryptedBase64: String, passphrase: String) {
        // Step 1: Decode Base64
        guard let encryptedData = Data(base64Encoded: encryptedBase64) else {
            print("❌ Base64 decoding failed")
            return
        }

        // Step 2: Extract Salt (First 8 bytes) and Ciphertext
        let salt = encryptedData.subdata(in: 8..<16)  // Extract Salt (Next 8 bytes after "Salted__")
        let ciphertext = encryptedData.subdata(in: 16..<encryptedData.count) // Remaining bytes

        // Step 3: Derive Key & IV using PBKDF2 (1000 iterations, SHA1, 48-byte output)
        do {
            let keyAndIV = try PKCS5.PBKDF2(
                password: passphrase.bytes,
                salt: salt.bytes,
                iterations: 1000,
                keyLength: 48,  // 32 bytes for Key + 16 bytes for IV = 48 bytes
                variant: .sha1
            ).calculate()

            let key = Array(keyAndIV[0..<32])  // First 32 bytes → AES-256 Key
            let iv = Array(keyAndIV[32..<48])  // Next 16 bytes → IV

            // Step 4: AES-256 CBC Decryption with PKCS7 Padding
            let aes = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7)
            let decryptedBytes = try aes.decrypt(ciphertext.bytes)

            
            // Step 6: Convert the decrypted bytes to a string (assuming it's UTF-8 encoded)
            if let decryptedString = String(bytes: decryptedBytes, encoding: .utf8) {
                print("Decrypted Message: \(decryptedString)")
            } else {
                print("Error: Decrypted data is not valid UTF-8")
            }

        } catch {
            print("❌ Decryption error: \(error)")
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions