Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
nirmal-opencrowd opened this issue Mar 7, 2025 · 0 comments

Comments

@nirmal-opencrowd
Copy link

nirmal-opencrowd commented Mar 7, 2025

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)")
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant