【问题标题】:AES Encryption in android and decryption in php and vice versaandroid中的AES加密和php中的解密,反之亦然
【发布时间】:2018-01-04 05:29:09
【问题描述】:

我正在尝试通过针对 https://aesencryption.net 测试我的代码来学习 AES。我之前在Base64.encodeBase64StringBase64.decodeBase64 // encode/decode Base64 中有一个错误。所以我以某种方式操纵 Base64 来解决错误。我认为,现在在我的应用程序中,文本已正确加密和解​​密。但是当我尝试加密或解密相同的文本服务器端(在 aesencryption.net)时,该站点无法解密我的加密字符串。请帮忙。

以下是我的代码:

public class MainActivity extends AppCompatActivity {

    static final String TAG = "SymmetricAlgorithmAES";
    private static SecretKeySpec secretKey ;
    private static byte[] key ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Original text
        // {"type":"Success","httpCode":"200","code":"200","message":{"pin":"11111"},"extra":""}
        String theTestText = "hi";
        TextView tvorig = (TextView)findViewById(R.id.tvorig);
        tvorig.setText("\n[ORIGINAL]:\n" + theTestText + "\n");
        final String strPssword = "android";
        setKey(strPssword);

        // Encode the original data with AES
        byte[] encodedBytes = null;
        try {
            Cipher c = Cipher.getInstance("AES");
            c.init(Cipher.ENCRYPT_MODE,secretKey);
            encodedBytes = c.doFinal(theTestText.getBytes());
        } catch (Exception e) {
            Log.e(TAG, "AES encryption error");
        }

        TextView tvencoded = (TextView)findViewById(R.id.tvencoded);
        tvencoded.setText("[ENCODED]:\n" +
                Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "\n");

        Log.d(TAG, Base64.encodeToString(encodedBytes, Base64.DEFAULT));


        // Decode the encoded data with AES
        byte[] decodedBytes = null;
        try {
            Cipher c = Cipher.getInstance("AES");
            c.init(Cipher.DECRYPT_MODE, secretKey);
            decodedBytes = c.doFinal(encodedBytes);
        } catch (Exception e) {
            Log.e(TAG, "AES decryption error");
        }
        TextView tvdecoded = (TextView)findViewById(R.id.tvdecoded);
        tvdecoded.setText("[DECODED]:\n" + new String(decodedBytes) + "\n");
    }



    public static void setKey(String myKey){
        MessageDigest sha = null;
        try {
            key = myKey.getBytes("UTF-8");
            System.out.println(key.length);
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16); // use only first 128 bit
            System.out.println(key.length);
            System.out.println(new String(key,"UTF-8"));
            secretKey = new SecretKeySpec(key, "AES");


        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

}

提前致谢。

【问题讨论】:

  • AES 有不同的加密模式,包括“salted”模式。在将网站克隆到应用程序之前,您必须知道网站使用的是什么模式。
  • 我正在尝试从aesencryption.net/#Java-aes-encryption-example 解密相同的代码。我也无法解密或加密。
  • AES 是一种分组密码,可以有different modes of operation。因此,如果您的网站(我假设是 PHP)使用一种操作模式,而您的应用程序使用另一种操作模式,您将获得不同的结果。除此之外,AES 结果取决于您使用的character encoding。确保两端相同。
  • @Pyromonk 感谢您抽出宝贵时间。这个案例实际上是在我的脑海中。但问题是,aes 网站本身已经给出了 java 中的代码和在线检查方式。在我的代码中,我也有一些小东西被操纵,因为我没有改变模式,所以我不确定它们是否会在网站上产生影响。因此,在应用程序中,我可以轻松地加密或解密字符串。但是当我使用该加密字符串并在 aes 网站中运行时,我无法对其进行解密。
  • 确保以下情况成立并运行另一个测试: 1)您加密的字符串仅包含 ANSI 字符(A-Z、a-z、_、-、0-9 等); 2)“加密密钥”在这两种情况下都是空白的; 3) 在这两种情况下,块大小都是 256 位。

标签: java php android android-studio aes


【解决方案1】:

我做了这样的事情,它确实有效;)

public class AESCrypter {
    private final Cipher cipher;
    private final SecretKeySpec key;
    private AlgorithmParameterSpec spec;


    public AESCrypter(String password) throws Exception
    {
        // hash password with SHA-256 and crop the output to 128-bit for key
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(password.getBytes("UTF-8"));
        byte[] keyBytes = new byte[32];
        System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);

        cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        key = new SecretKeySpec(keyBytes, "AES");
        spec = getIV();
    }

    public AlgorithmParameterSpec getIV()
    {
        byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
        IvParameterSpec ivParameterSpec;
        ivParameterSpec = new IvParameterSpec(iv);

        return ivParameterSpec;
    }

    public String encrypt(String plainText) throws Exception
    {
        cipher.init(Cipher.ENCRYPT_MODE, key, spec);
        byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
        String encryptedText = new String(Base64.encode(encrypted, Base64.DEFAULT), "UTF-8");

        return encryptedText;
    }

    public String decrypt(String cryptedText) throws Exception
    {
        cipher.init(Cipher.DECRYPT_MODE, key, spec);
        byte[] bytes = Base64.decode(cryptedText, Base64.DEFAULT);
        byte[] decrypted = cipher.doFinal(bytes);
        String decryptedText = new String(decrypted, "UTF-8");

        return decryptedText;
    }
}

这样调用这个类:

 try {
            AESCrypter _crypt = new AESCrypter("password");
            String output = "";
            String plainText = "top secret message";
            output = _crypt.encrypt(plainText); //encrypt
            System.out.println("encrypted text=" + output);
            output = _crypt.decrypt(output); //decrypt
            System.out.println("decrypted text=" + output);
        } catch (Exception e) {
            e.printStackTrace();
        }

对于 iPhone(代码在这里):https://github.com/Gurpartap/AESCrypt-ObjC

希望此代码也适用于您 :)

【讨论】:

    【解决方案2】:

    PHP 代码默认使用 CBC 模式,而您的 Java 代码没有指定相同的模式,并将其留给底层实现。如果我没记错的话,它可能是ECB/PKCS5Padding。您的 PHP 实现使用没有填充的“CBC”(默认情况下,mcrypt 不支持填充,但您可以手动进行)。

    在使用不同平台时,非常具体的模式、填充和字符集非常重要,否则您将遇到不同的默认设置。

    尝试按如下方式初始化您的密码:Cipher.getInstance("AES/CBC/NoPadding");

    【讨论】:

    • 感谢您的宝贵时间。我操纵代码,现在它工作正常。 :)
    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2016-09-22
    • 1970-01-01
    • 2012-08-01
    • 2021-04-13
    • 2023-03-23
    相关资源
    最近更新 更多