我知道关于这个问题有几个问题,但没有人回答我的问题,我在android中使用RSA加密,首先尝试在本机java中运行得非常好,每次运行时我都返回了不同的加密但是我总是得到相同的,并且总是一个糟糕的字符串。
byte[] usernameA = cifrador.cifra("1035861042", getAssets().open("public.key"));
byte[] encoded = Base64.encodeBase64(usernameA);
String username = new String(encoded);
public byte[] cifra(Object msjO, InputStream fileNamePrivateKey) throws Exception {
try {
ObjectInputStream restore = new ObjectInputStream(fileNamePrivateKey);
PublicKey llave = (PublicKey) restore.readObject();
String msj = (String)msjO;
restore.close();
if (llave != null) {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance("RSA");
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, llave);
byte[] encrypted = cipher.doFinal(msj.getBytes());
return encrypted;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
在本机java中,我执行以下操作
static final String PUBLIC_KEY_FILE = "C:/keys/public.key";
inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
final PublicKey publicKey = (PublicKey) inputStream.readObject();
final byte[] cipherText = encrypt(originalText, publicKey);
public static byte[] encrypt(String text, PublicKey key) {
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}