Android的密码加密/解密 [英] Android Cipher encrypt/decrypt

查看:457
本文介绍了Android的密码加密/解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用密码来加密和解密消息:

I'm using cipher to encrypt and decrypt messages:

public String encrypt(String string) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
  cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
  byte[] stringBytes = string.getBytes("UTF-8");
  byte[] encryptedBytes = cipher.doFinal(stringBytes);
  return android.util.Base64.encodeToString(encryptedBytes, android.util.Base64.DEFAULT);
}

public String decrypt(String string) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
  cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
  byte[] stringBytes = android.util.Base64.decode(string.getBytes(), android.util.Base64.DEFAULT);
  byte[] decryptedBytes = cipher.doFinal(stringBytes);
  return new String(decryptedBytes,"UTF-8");
}

出于某种原因,虽然我用的Base64为en code和德$ C C字符串$,我仍然得到这个错误:

For some reason although I'm using Base64 to encode and decode the string, I still get this error:

javax.crypto.IllegalBlockSizeException:最后一个块不完整的解密

javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

我是什么做错了吗?

编辑:

这是我的JSONObject - 我试图解密M:

This is my JSONObject - I'm trying to decrypt the "m":

{"m":"Cu7FR2be0E6ZP2BrZaLU2ZWQSfycNg0-fPibphTIZno\r\n"}

奇怪的是,错误只出现在Android系统。我的服务器是用Java编写的,我使用Apache的Base64 EN codeR,它的伟大工程。

The weird thing is that the error only appears in Android. My server is written in Java and I'm using Apache Base64 encoder and it works great.

推荐答案

您需要转换BASE-64第一。

You need to convert Base-64 first.

codeED =加密(Base64.en code(MyString的,Base64.DEFAULT));

CODEED = encrypt(Base64.encode(MYSTRING, Base64.DEFAULT));

MyString的= Base64.de code(解密(codeED),Base64.DEFAULT);

MYSTRING = Base64.decode(decrypt(CODEED), Base64.DEFAULT);

这里是一个链接的http://android$c$cmonkey.blogspot.com/2010/03/how-to-base64-en$c$c-de$c$c-android.html

这篇关于Android的密码加密/解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆