у меня стандартная задача:
Ключи генерятся на сервере библиотекой phpseclib/phpseclib - на самом сервере кодирование-декодирование работает. Проверял доставку, посылал уже зашифрованный пароль на клиента и с клиента отправлял на сервер, все работает и расшифровывается.
Но в приложение это не работает.
Вот функции кодирования в приложениии:
String key = jobj.optString("public_key","");
byte[] data = Base64.decode(key, Base64.NO_WRAP);
String text = new String(data, "UTF-8");
PublicKey pubKey = Tools.getPublicKeyFromPemFormat(text,false);
String passEncode = Tools.encrypt2(pass, pubKey ) ;
Log.e("passEncode",passEncode);
public static PublicKey getPublicKeyFromPemFormat(String PEMString,
boolean isFilePath) throws IOException, NoSuchAlgorithmException,
InvalidKeySpecException {
BufferedReader pemReader = null;
if (isFilePath) {
pemReader = new BufferedReader(new InputStreamReader(
new FileInputStream(PEMString)));
} else {
pemReader = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(PEMString.getBytes("UTF-8"))));
}
StringBuffer content = new StringBuffer();
String line = null;
while ((line = pemReader.readLine()) != null) {
if (line.indexOf("-----BEGIN PUBLIC KEY-----") != -1) {
while ((line = pemReader.readLine()) != null) {
if (line.indexOf("-----END PUBLIC KEY") != -1) {
break;
}
content.append(line.trim());
}
break;
}
}
if (line == null) {
throw new IOException("PUBLIC KEY" + " not found");
}
Log.i("PUBLIC KEY: ", "PEM content = : " + content.toString());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(content.toString(), Base64.NO_WRAP)));
}
public static String encrypt(String text, PublicKey key) {
byte[] cipherText = null;
try {
// 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, key);
cipherText = cipher.doFinal(text.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
return Base64.encodeToString(cipherText, Base64.NO_WRAP);
}
Если здесь ошибка?
Кодируя этими функциями получаю результат - строка которая потом не декодируется с правильным приватным ключом.
Огромное спасибо andreymal , я нашел это, вернее вы подсказали.
Нужно было проставить в PHP по умолчанию
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
И в финкции на java
изменить одну строку
public static String encrypt2(String text, PublicKey key) {
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
return Base64.encodeToString(cipherText, Base64.NO_WRAP);
}
А то я уж подумал, что вообще не понимаю как это работает)). Спасибо.
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости