我制作了一个用于发送安全短信的Android应用。 我目前有以下代码(Iam使用256进行测试)
public void generateKey() throws NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException,BadPaddingException,InvalidKeyException{
try{
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(256);
kp = kpg.genKeyPair();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(getBaseContext(), e.toString(),Toast.LENGTH_LONG).show();
}
}
public byte[] RSAEncrypt(final String plain) throws NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
try {
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes("UTF-8"));
}catch (Exception e){
e.printStackTrace();
Toast.makeText(getBaseContext(),e.toString(),Toast.LENGTH_LONG).show();
}
return encryptedBytes;
}
public void enviaSMS(View view) {
EditText key = (EditText) findViewById(R.id.publicKey);
EditText phoneNumber = (EditText) findViewById(R.id.phoneNumber);
EditText text = (EditText) findViewById(R.id.TextMessage);
String keyText = key.getText().toString();
String number = phoneNumber.getText().toString();
String sms = text.getText().toString();
if (!keyText.equals("") && !number.equals("") && !sms.equals("")) {
try {
byte[] encriptedSMS= RSAEncrypt(sms);
Log.i("teste",new String(encriptedSMS));
Log.i("teste",new String(encriptedSMS, "UTF-8"));
Toast.makeText(getBaseContext(), new String(encriptedSMS, "UTF-8"), Toast.LENGTH_SHORT).show(); // ou send?:3
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, new String(encriptedSMS,"UTF-8"), null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
}
当我写下像#34的字符串时,你好我是john doe"我得到类似2e2??????24sfe??
我正在制作UTF-8字符串,因此加密损坏的问题可能是什么?
答案 0 :(得分:3)
new String(encriptedSMS,"UTF-8")
你的问题就在这里。 encriptedSMS
不包含UTF-8编码文本,因此这是错误的。
没有正确的方法将字节数组“转换”为String
,除非字节数组包含编码文本(就像从someString.getBytes("UTF-8")
获得的那样)。
但是,有一些方法可以将字节数组编码为字符串。 Base64就是这样一种编码。由于这是Android,您可以使用android.util.Base64
类:
String encodedSMS = Base64.encodeToString(encriptedSMS, Base64.DEFAULT)
并对其进行解码,例如:
byte[] encriptedSMS = Base64.decode(encodedSMS, Base64.DEFAULT)