coder hard
coder hard

Reputation: 13

PBKDF2WithHmacSHA512 and AES encryption from java to swift

   public static SecretKeySpec createKey(String secureKey, String secureId)
            throws InvalidKeySpecException, NoSuchAlgorithmException {
        
        byte[] salt = secureId.getBytes();
        byte[] securekeyBytes = android.util.Base64.decode(secureKey, android.util.Base64.DEFAULT);
        String finalKey = new String(securekeyBytes, StandardCharsets.UTF_8);
        
        PBEKeySpec spec = new PBEKeySpec(finalKey.toCharArray(), salt,
                Integer.valueOf(10000),
                Integer.valueOf(256));
       
        SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
                .generateSecret(spec);
        return new SecretKeySpec(key.getEncoded(), "AES");
    }

This is my java code for encryption, I am trying to implement the same in swift, but not getting proper solution, so what is the equivalent code for this java code snippet in swift language?

    func createKey(secretKey: String, secretId: String) throws -> SymmetricKey {
        let salt = secretId.data(using: .utf8)!
        let accessKeyData = Data(base64Encoded: accessKey)!
        let finalKey = String(data: secretKeyData, encoding: .utf8)!
        
        let keyData = try! deriveKey(password: finalKey, salt: salt, iterations: 10000, keyLength: 256 / 8)
        
        return SymmetricKey(data: keyData)
    }

    func deriveKey(password: String, salt: Data, iterations: Int, keyLength: Int) throws -> Data {
        var derivedKeyData = Data(count: keyLength)
        let passwordData = password.data(using: .utf8)!
        
        let result = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes in
            salt.withUnsafeBytes { saltBytes in
                CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2),
                                     password,
                                     passwordData.count,
                                     saltBytes,
                                     salt.count,
                                     CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA512),
                                     UInt32(iterations),
                                     derivedKeyBytes,
                                     keyLength)
            }
        }
        
        if result != kCCSuccess {
            throw NSError(domain: NSOSStatusErrorDomain, code: Int(result), userInfo: nil)
        }
        
        return derivedKeyData
    }

I used this method but its nit giving a proper expected result, so is there any way to achieve the same in simple code format

Upvotes: 1

Views: 315

Answers (0)

Related Questions