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

时间:2018-01-04 05:29:10

标签: java php android android-studio aes

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

    }

}

提前致谢。

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

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

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

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