Преобразуйте строку в Publi c Key и используйте ее в качестве шифрования - PullRequest
0 голосов
/ 09 мая 2020
W/System.err: javax.crypto.IllegalBlockSizeException: error:04000072:RSA routines:OPENSSL_internal:DATA_TOO_LARGE_FOR_KEY_SIZE
W/System.err:     at com.android.org.conscrypt.NativeCrypto.RSA_public_encrypt(Native Method)
        at com.android.org.conscrypt.OpenSSLCipherRSA$DirectRSA.doCryptoOperation(OpenSSLCipherRSA.java:396)
        at com.android.org.conscrypt.OpenSSLCipherRSA.engineDoFinal(OpenSSLCipherRSA.java:314)
        at javax.crypto.Cipher.doFinal(Cipher.java:2055)
        at com.example.jainishadabhi.mysocialnetwork.util.PrefsManager.encryptAsymmetric(PrefsManager.java:113)

Код для шифрования

public static byte[] encryptAsymmetric(byte[] plaintext, PublicKey key) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] cipherText = cipher.doFinal(plaintext);
    return cipherText;
}

public static String decryptAsymmetric(byte[] cipherText, PrivateKey key) {
    try {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedText = cipher.doFinal(cipherText);
        System.out.println("check for Decryption:" + decryptedText);
        return new String(decryptedText);
    } catch(Exception e) {
        e.printStackTrace();
    }
    return null;
}

//**Code to get convert String to Public Key type**

byte[] publicBytes = Base64.decode(publicKeyData, Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(spec);

//Encrypted group key with public key of the requested used

byte[] encryptedDataGroupKey = obj.encryptAsymmetric(groupkeyDataBytes, pubKey);
String encryptedDataGroupKeyStr = obj.encoderfun(encryptedDataGroupKey);
...