Javax.crypto.BadPaddingException: ошибка: 1e000065: Функции шифрования: OPENSSL_internal:BAD_DECRYPT во время расшифровкAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Javax.crypto.BadPaddingException: ошибка: 1e000065: Функции шифрования: OPENSSL_internal:BAD_DECRYPT во время расшифровк

Сообщение Anonymous »

Я пытаюсь создать приложение для Android на Kotlin. После сохранения информации о пользователе (полученной из моего API) в файле на устройстве я запускаю метод для ее расшифровки, но он выдает "javax.crypto" .BadPaddingException: ошибка: 1e000065: Функции шифрования: OPENSSL_internal:BAD_DECRYPT». И я не могу понять почему, кто-нибудь поможет?
Это код функции дешифрования:
package com.example.uniapp
import android.annotation.SuppressLint
import android.os.Build
import androidx.annotation.RequiresApi
import java.nio.charset.StandardCharsets
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

object EncryptionUtils {

@SuppressLint("NewApi")
fun decrypt(encryptedText: String, aesKey: String): String {
// Decode the Base64 encoded string
val fullCipher = Base64.getDecoder().decode(encryptedText)

// Create an AES cipher instance
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
val blockSize = cipher.blockSize

// Extract the IV and the actual cipher text
val iv = fullCipher.copyOfRange(0, blockSize)
val cipherBytes = fullCipher.copyOfRange(blockSize, fullCipher.size)

// Setup the key and IV
val keySpec = SecretKeySpec(aesKey.toByteArray(StandardCharsets.UTF_8), "AES")
val ivSpec = IvParameterSpec(iv)

// Initialize the cipher for decryption
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec)

// Perform decryption
val decryptedBytes = cipher.doFinal(cipherBytes)

// Convert decrypted bytes to string
return String(decryptedBytes, StandardCharsets.UTF_8)
}
}

И это действие входа в систему, которое вызывает расшифровку (оно еще не завершено)
package com.example.uniapp
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.example.uniapp.network.NetworkService
import com.example.uniapp.util.EncryptionUtils
import com.example.uniapp.util.FileStorageUtils
import com.example.uniapp.util.GlobalVariables

class LoginActivity : AppCompatActivity() {

private val apiUrl = "${GlobalVariables.apiCommonUrl}users/userinfo"
private val aesKey = "${GlobalVariables.AESKey}" // Replace with your actual key
private lateinit var networkService: NetworkService

@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_screen)

networkService = NetworkService(apiUrl)

val usernameEditText = findViewById(R.id.usernameField)
val passwordEditText = findViewById(R.id.passwordField)
val loginButton = findViewById(R.id.loginButton)

loginButton.setOnClickListener {
val username = usernameEditText.text.toString()
val password = passwordEditText.text.toString()
loginUser(username, password)
}
}

@RequiresApi(Build.VERSION_CODES.O)
private fun loginUser(username: String, password: String) {
networkService.loginUser(username, password) { success, encryptedUserInfo ->
if (success && encryptedUserInfo != null) {
FileStorageUtils.saveToFile(this, "user_info.txt", encryptedUserInfo)
val intent = Intent(this, HomepageProfessor::class.java)
startActivity(intent)
decryptUserInfo(encryptedUserInfo)
} else {
runOnUiThread {
Toast.makeText(this, "Login failed", Toast.LENGTH_SHORT).show()
}
}
}
}

@RequiresApi(Build.VERSION_CODES.O)
private fun decryptUserInfo(encryptedUserInfo: String) {
val decryptedUserInfo = EncryptionUtils.decrypt(encryptedUserInfo, aesKey)
runOnUiThread {
if (decryptedUserInfo != null) {
Toast.makeText(this, "Decrypted User Info: $decryptedUserInfo", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, "Decryption failed", Toast.LENGTH_SHORT).show()
}
}
}
}


Размер AESKey составляет 32 байта, поэтому он правильный, и этот код учитывает шифрование API.
Это код шифрования в API и в .NET
public string Encrypt(string plainText)
{
using var aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes(options.Value.AESKey);
aes.GenerateIV();
using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using var ms = new MemoryStream();
using var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
using (var sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
var iv = aes.IV;
var encryptedContent = ms.ToArray();
var result = new byte[iv.Length + encryptedContent.Length];
Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
Buffer.BlockCopy(encryptedContent, 0, result, iv.Length, encryptedContent.Length);
return Convert.ToBase64String(result);
}

public async Task EncryptAsync(string plainText)
{
return await Task.FromResult(Encrypt(plainText));
}

И это функция расшифровки, которая есть у меня в API, но я не хочу использовать ее в клиентском приложении в целях повышения производительности.
public string Decrypt(string encryptedText)
{
var fullCipher = Convert.FromBase64String(encryptedText);
using var aes = Aes.Create();
var iv = new byte[aes.BlockSize / 8];
var cipher = new byte[fullCipher.Length - iv.Length];
Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, cipher.Length);
aes.Key = Encoding.UTF8.GetBytes(options.Value.AESKey);
aes.IV = iv;
using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using var ms = new MemoryStream(cipher);
using var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
using var sr = new StreamReader(cs);
var decryptedText = sr.ReadToEnd();
return decryptedText;
}

public async Task DecryptAsync(string encryptedText)
{
return await Task.FromResult(Decrypt(encryptedText));
}


Подробнее здесь: https://stackoverflow.com/questions/788 ... ssl-intern
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»