0

我知道关于这个主题有几个问题,但没有人回答我的问题,我在 android 中使用 RSA 加密,首先在本机 java 中尝试过,效果很好,每次运行时我都会返回不同的加密,但 android 我总是得到相同的,并且总是一个坏字符串。

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

0 回答 0