繁体   English   中英

android 中的 AES 加密和 php 中的解密,反之亦然

[英]AES Encryption in android and decryption in php and vice versa

我正在尝试通过针对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();
        }

    }

}

提前致谢。

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

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;
    }
}

像这样调用这个 class:

 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

希望这段代码也适合你:)

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

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

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

    fun encrypt(encrypted: String): String? {
        try {
            val secretKey = "secretKey" //The secret key, 32 bytes string.
            val ivKey = "ivKey" // The initialization vector, 16 bytes string.
            val iv = IvParameterSpec(hashIV.toByteArray(Charsets.UTF_8))
            val skySpec = SecretKeySpec(hashKey.toByteArray(Charsets.UTF_8), "AES-256-CBC")
            val cipher: Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
            cipher.init(Cipher.ENCRYPT_MODE, skySpec, iv)
            val original: ByteArray = cipher.doFinal(encrypted.toByteArray())
            return Base64.encode(
                Base64.encodeToString(original, Base64.NO_WRAP).toByteArray(charset("UTF-8")),
                Base64.NO_WRAP
            ).decodeToString()
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
        return null
    }

    fun decrypt(encrypted: String?): String? {
        try {
            val secretKey = "secretKey" //The secret key, 32 bytes string.
            val ivKey = "ivKey" // The initialization vector, 16 bytes string.
            val iv = IvParameterSpec(hashIV.toByteArray(Charsets.UTF_8))
            val skySpec = SecretKeySpec(hashKey.toByteArray(Charsets.UTF_8), algorithm)
            val cipher: Cipher = Cipher.getInstance(transformation)
            cipher.init(Cipher.DECRYPT_MODE, skySpec, iv)
            val original: ByteArray = cipher.doFinal(
                Base64.decode(
                    Base64.decode(encrypted, Base64.NO_WRAP),
                    Base64.NO_WRAP
                )
            )
            return original.decodeToString()
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
        return null
    }

openssl_encrypt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM