android - 相同的 AES 代码 swift 2 和 android

标签 android ios swift swift2

我是 swift 的新手。我在 android 中有 AES 代码,所以我需要 AES 代码用于 swift 2。我找到了很多 AES 代码,但没有找到适用于 swift 2 和 Android 的相同代码。请给我建议。

Android 的代码:

public class AES {
public static String SALT = "8e0b86611d5922ffd57fcc053644ff6d73459b2b";
public static SecretKeySpec getKey(String myKey) {
    MessageDigest sha = null;
    byte[] key;
    try {
        key = myKey.getBytes("UTF-8");
        sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 16); // use only first 128 bit
        return new SecretKeySpec(key, "AES");
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

public static String encrypt(String strToEncrypt, String password) {
    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, getKey(password));
        return Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
    } catch (Exception e) {
        System.out.println("Error while encrypting: " + e.toString());
    }
    return null;

}

public static String decrypt(String strToDecrypt, String password) {
    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, getKey(password));
        return new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
    } catch (Exception e) {
        System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
}


public static void main(String args[]) {
    String text = "Hello World!";
    String encrypt = AES.encrypt(text,SALT);

    System.out.println("String to Encrypt: " + text);
    System.out.println("Encrypted: " + encrypt);

    System.out.println("String To Decrypt : " + encrypt);
    System.out.println("Decrypted : " + AES.decrypt(encrypt,SALT));
}

}

最佳答案

我建议不要编写自己的 AES 加密并使用 CryptoSwift相反。

关于android - 相同的 AES 代码 swift 2 和 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33498037/

相关文章:

ios - 如何保存 uitextfield 以便文本从 View Controller 保留到 View Controller

android - 在xamarin studio中添加第三方dll

ios - 位置管理器不会快速更新位置。 AlertView 消失

android - 如果 SQL 表达式具有带 SUBSELECT 查询的 LENGTH 函数,则将其转换为 SQLite

ios - 适用于所有屏幕尺寸的 Storyboard

ios - Grand Central Dispatch 和并发任务

swift - 未调用 UICollectionView insetForSectionAtIndex

swift - Firebase Analytics 代替 Google Analytics 启动

java - libgdx 3d无限滚动地板

java - 如何在 Android 应用程序中的每个 ListView 项目文本之前添加图标?