Когда мы пытаемся расшифровать ответ (зашифрованные данные), с нашим закрытым ключом мы получаем ошибку:-< /p>
Исключение текста цифера. преобразовать это < /p>
package com.sso.encryption;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import java.util.Arrays;
import java.util.Base64;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
public class RSAEncryptionWithAES256 {
PublicKey publicKey = null;
PrivateKey privateKey = null;
private static final int MAX_DE_RSA_BLOCK_SIZE = 256;
private static final int MAX_RSA_BLOCK_SIZE = 190;
public RSAEncryptionWithAES256() throws Exception {
// Add BouncyCastle provider (needed for OAEPWithSHA-256)
Security.addProvider(new BouncyCastleProvider());
// Load Public and Private Key from PEM files (with AES-256 encrypted private key)
publicKey = loadPublicKey("enc1_public_key.pem");
privateKey = loadEncryptedPrivateKey("enc2_private_key.pem");
}
public static void main(String[] args) throws Exception {
String req ="{\r\n"
+ " \"CorporateId\": \"40682399\",\r\n"
+ " ]\r\n"
+ "}";
RSAEncryptionWithAES256 rsaEncryptionWithAES256 = new RSAEncryptionWithAES256();
String encryptAndEncodeToBase64 = rsaEncryptionWithAES256.encryptAndEncodeToBase64(req);
System.out.println("Non Reverse: "+encryptAndEncodeToBase64);
String decryptedMessage = rsaEncryptionWithAES256.decodeAndDecryptFromBase64(encryptAndEncodeToBase64);
// String decryptedMsg = new String(decryptedMessage);
System.out.println("Non Reverse : "+decryptedMessage);
String encryptAndEncodeToBase64PublicKey = rsaEncryptionWithAES256.encryptAndEncodeToBase64PublicKey(decryptedMessage);
System.out.println("Reverse: "+encryptAndEncodeToBase64PublicKey);
String decodeAndDecryptFromBase64PrivateKey = rsaEncryptionWithAES256.decodeAndDecryptFromBase64PrivateKey(encryptAndEncodeToBase64PublicKey);
System.out.println("Reverse Rep : "+decodeAndDecryptFromBase64PrivateKey);
}
// Method to load the Public Key from a PEM file
public static PublicKey loadPublicKey(String filename) throws Exception {
FileInputStream fis = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
StringBuilder pemContent = new StringBuilder();
while ((line = br.readLine()) != null) {
if (!line.startsWith("-----")) {
pemContent.append(line);
}
}
byte[] encoded = Base64.getDecoder().decode(pemContent.toString());
X509EncodedKeySpec spec = new X509EncodedKeySpec(encoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(spec);
}
// Method to load the Private Key from a PEM file (with passphrase for AES-256 decryption)
public static PrivateKey loadEncryptedPrivateKey(String filename) throws Exception {
// Load the encrypted private key PEM file
FileReader pemFileReader = new FileReader(filename);
PEMParser pemParser = new PEMParser(pemFileReader);
// Read the encrypted private key info
PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemParser.readObject();
pemParser.close();
// Create the decryptor provider using a password (this should match the password used to encrypt the key) & add you pass phrase
char[] password = "demo".toCharArray();
JceOpenSSLPKCS8DecryptorProviderBuilder decryptorProviderBuilder = new JceOpenSSLPKCS8DecryptorProviderBuilder();
InputDecryptorProvider decryptorProvider = decryptorProviderBuilder.build(password);
// Decrypt the private key
PrivateKeyInfo privateKey = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decryptorProvider);
// To use this key with Java's standard APIs (for example, signing), you can convert it like this:
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// If you need to convert to a standard PrivateKey format, you can create the PKCS8EncodedKeySpec
byte[] encodedKey = privateKey.getEncoded();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
PrivateKey standardPrivateKey = keyFactory.generatePrivate(keySpec);
System.out.println("Standard Java Private Key: " + standardPrivateKey);
return standardPrivateKey;
}
// Method to encrypt data in chunks using OAEP padding
public byte[] encryptInChunksUsingPrivateKey(byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
int dataLength = data.length;
byte[] encryptedData = new byte[0];
// Encrypt in chunks
for (int i = 0; i < dataLength; i += MAX_RSA_BLOCK_SIZE) {
int end = Math.min(i + MAX_RSA_BLOCK_SIZE, dataLength);
byte[] chunk = Arrays.copyOfRange(data, i, end);
byte[] encryptedChunk = cipher.doFinal(chunk);
encryptedData = combineArrays(encryptedData, encryptedChunk);
}
return encryptedData;
}
// Method to decrypt data in chunks
public byte[] decryptInChunksUsingPublicKey(byte[] encryptedData) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
int encryptedDataLength = encryptedData.length;
byte[] decryptedData = new byte[0];
// Decrypt in chunks (each chunk can be at most MAX_RSA_BLOCK_SIZE bytes)
for (int i = 0; i < encryptedDataLength; i += MAX_DE_RSA_BLOCK_SIZE) {
int end = Math.min(i + MAX_DE_RSA_BLOCK_SIZE, encryptedDataLength);
byte[] chunk = Arrays.copyOfRange(encryptedData, i, end);
// Decrypt the chunk
byte[] decryptedChunk = cipher.doFinal(chunk);
decryptedData = combineDecodeArrays(decryptedData, decryptedChunk);
}
return decryptedData;
}
// Method to combine arrays
private byte[] combineDecodeArrays(byte[] first, byte[] second) {
byte[] result = new byte[first.length + second.length];
System.arraycopy(first, 0, result, 0, first.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
// Method to combine arrays
private byte[] combineArrays(byte[] first, byte[] second) {
byte[] result = new byte[first.length + second.length];
System.arraycopy(first, 0, result, 0, first.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public String encryptAndEncodeToBase64(String data) throws Exception {
// Encrypt the JSON string
byte[] encryptedData = encryptInChunksUsingPrivateKey(data.getBytes());
// Return the encrypted data encoded in Base64
return Base64.getEncoder().encodeToString(encryptedData);
}
// Decode base64 and decrypt the data back to original object
public String decodeAndDecryptFromBase64(String base64Data) throws Exception {
// Decode the Base64 to get the encrypted data
byte[] encryptedData = Base64.getDecoder().decode(base64Data);
// Decrypt the data
byte[] decryptedData = decryptInChunksUsingPublicKey(encryptedData);
// Convert decrypted byte array back to string
return new String(decryptedData);
}
public String encryptAndEncodeToBase64PublicKey(String data) throws Exception {
// Encrypt the JSON string
byte[] encryptedData = encryptInChunksUsingPublicKey(data.getBytes());
// Return the encrypted data encoded in Base64
return Base64.getEncoder().encodeToString(encryptedData);
}
// Decode base64 and decrypt the data back to original object
public String decodeAndDecryptFromBase64PrivateKey(String base64Data) throws Exception {
// Decode the Base64 to get the encrypted data
byte[] encryptedData = Base64.getDecoder().decode(base64Data);
// Decrypt the data
byte[] decryptedData = decryptInChunksUsingPrivateKey(encryptedData);
// Convert decrypted byte array back to string
return new String(decryptedData);
}
// Method to encrypt data in chunks using OAEP padding
public byte[] encryptInChunksUsingPublicKey(byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
// cipher.init(Cipher.ENCRYPT_MODE, privateKey);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int dataLength = data.length;
byte[] encryptedData = new byte[0];
// Encrypt in chunks
for (int i = 0; i < dataLength; i += MAX_RSA_BLOCK_SIZE) {
int end = Math.min(i + MAX_RSA_BLOCK_SIZE, dataLength);
byte[] chunk = Arrays.copyOfRange(data, i, end);
byte[] encryptedChunk = cipher.doFinal(chunk);
encryptedData = combineArrays(encryptedData, encryptedChunk);
}
return encryptedData;
}
// Method to decrypt data in chunks
public byte[] decryptInChunksUsingPrivateKey(byte[] encryptedData) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int encryptedDataLength = encryptedData.length;
byte[] decryptedData = new byte[0];
// Decrypt in chunks (each chunk can be at most MAX_RSA_BLOCK_SIZE bytes)
for (int i = 0; i < encryptedDataLength; i += MAX_DE_RSA_BLOCK_SIZE) {
int end = Math.min(i + MAX_DE_RSA_BLOCK_SIZE, encryptedDataLength);
byte[] chunk = Arrays.copyOfRange(encryptedData, i, end);
// Decrypt the chunk
byte[] decryptedChunk = cipher.doFinal(chunk);
decryptedData = combineDecodeArrays(decryptedData, decryptedChunk);
}
return decryptedData;
}
}
< /code>
и преобразованный код C# - < /p>
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Asn1.Pkcs;
namespace com.sso.encryption
{
public class RSAEncryptionWithAES256
{
public AsymmetricKeyParameter publicKey = null;
public AsymmetricKeyParameter privateKey = null;
private static readonly int MAX_DE_RSA_BLOCK_SIZE = 256;
private static readonly int MAX_RSA_BLOCK_SIZE = 190;
public RSAEncryptionWithAES256()
{
try
{
// Add BouncyCastle provider (needed for OAEPWithSHA-256)
// In .NET, BouncyCastle is used via its API, no need to add as provider.
// Load Public and Private Key from PEM files (with AES-256 encrypted private key)
publicKey = loadPublicKey("enc1_public_key.pem");
privateKey = loadEncryptedPrivateKey("enc2_private_key.pem");
}
catch (Exception ex)
{
throw new Exception("Error in constructor: " + ex.Message, ex);
}
}
public static void Main(string[] args)
{
try
{
string req = "{\r\n"
+ "}";
RSAEncryptionWithAES256 rsaEncryptionWithAES256 = new RSAEncryptionWithAES256();
string encryptAndEncodeToBase64 = rsaEncryptionWithAES256.encryptAndEncodeToBase64(req);
Console.WriteLine("Non Reverse: " + encryptAndEncodeToBase64);
string decryptedMessage = rsaEncryptionWithAES256.decodeAndDecryptFromBase64(encryptAndEncodeToBase64);
// string decryptedMsg = new string(decryptedMessage);
Console.WriteLine("Non Reverse : " + decryptedMessage);
string encryptAndEncodeToBase64PublicKey = rsaEncryptionWithAES256.encryptAndEncodeToBase64PublicKey(decryptedMessage);
Console.WriteLine("Reverse: " + encryptAndEncodeToBase64PublicKey);
string decodeAndDecryptFromBase64PrivateKey = rsaEncryptionWithAES256.decodeAndDecryptFromBase64PrivateKey(encryptAndEncodeToBase64PublicKey);
Console.WriteLine("Reverse Rep : " + decodeAndDecryptFromBase64PrivateKey);
}
catch (Exception ex)
{
Console.WriteLine("Exception in Main: " + ex.Message);
}
}
// Method to load the Public Key from a PEM file
public static AsymmetricKeyParameter loadPublicKey(string filename)
{
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
{
StringBuilder pemContent = new StringBuilder();
string line;
while ((line = sr.ReadLine()) != null)
{
if (!line.StartsWith("-----"))
{
pemContent.Append(line);
}
}
byte[] encoded = Convert.FromBase64String(pemContent.ToString());
return PublicKeyFactory.CreateKey(encoded);
}
}
// Method to load the Private Key from a PEM file (with passphrase for AES-256 decryption)
public static AsymmetricKeyParameter loadEncryptedPrivateKey(string filename)
{
using (StreamReader sr = new StreamReader(filename))
{
// Create the PEM reader with a password finder using the passphrase "demo"
PemReader pemReader = new PemReader(sr, new MyPasswordFinder("demo"));
object keyObject = pemReader.ReadObject();
pemReader.Reader.Close();
AsymmetricKeyParameter privateKeyParam = null;
if (keyObject is AsymmetricCipherKeyPair)
{
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)keyObject;
privateKeyParam = keyPair.Private;
}
else if (keyObject is AsymmetricKeyParameter)
{
privateKeyParam = (AsymmetricKeyParameter)keyObject;
}
else if (keyObject is Pkcs8EncryptedPrivateKeyInfo)
{
// If the object is of type Pkcs8EncryptedPrivateKeyInfo, decrypt it using the password.
Pkcs8EncryptedPrivateKeyInfo encInfo = (Pkcs8EncryptedPrivateKeyInfo)keyObject;
PrivateKeyInfo pkInfo = encInfo.DecryptPrivateKeyInfo(new MyPasswordFinder("demo"));
privateKeyParam = PrivateKeyFactory.CreateKey(pkInfo);
}
Console.WriteLine("Standard .NET Private Key: " + privateKeyParam.ToString());
return privateKeyParam;
}
}
// Method to encrypt data in chunks using OAEP padding with private key
public byte[] encryptInChunksUsingPrivateKey(byte[] data)
{
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest());
cipher.Init(true, privateKey);
int dataLength = data.Length;
byte[] encryptedData = new byte[0];
// Encrypt in chunks
for (int i = 0; i < dataLength; i += MAX_RSA_BLOCK_SIZE)
{
int end = Math.Min(i + MAX_RSA_BLOCK_SIZE, dataLength);
byte[] chunk = new byte[end - i];
Array.Copy(data, i, chunk, 0, end - i);
byte[] encryptedChunk = cipher.ProcessBlock(chunk, 0, chunk.Length);
encryptedData = combineArrays(encryptedData, encryptedChunk);
}
return encryptedData;
}
// Method to decrypt data in chunks using public key
public byte[] decryptInChunksUsingPublicKey(byte[] encryptedData)
{
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest());
cipher.Init(false, publicKey);
int encryptedDataLength = encryptedData.Length;
byte[] decryptedData = new byte[0];
// Decrypt in chunks (each chunk can be at most MAX_DE_RSA_BLOCK_SIZE bytes)
for (int i = 0; i < encryptedDataLength; i += MAX_DE_RSA_BLOCK_SIZE)
{
int end = Math.Min(i + MAX_DE_RSA_BLOCK_SIZE, encryptedDataLength);
byte[] chunk = new byte[end - i];
Array.Copy(encryptedData, i, chunk, 0, end - i);
// Decrypt the chunk
byte[] decryptedChunk = cipher.ProcessBlock(chunk, 0, chunk.Length);
decryptedData = combineDecodeArrays(decryptedData, decryptedChunk);
}
return decryptedData;
}
// Method to combine arrays
private byte[] combineDecodeArrays(byte[] first, byte[] second)
{
byte[] result = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, result, 0, first.Length);
Buffer.BlockCopy(second, 0, result, first.Length, second.Length);
return result;
}
// Method to combine arrays
private byte[] combineArrays(byte[] first, byte[] second)
{
byte[] result = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, result, 0, first.Length);
Buffer.BlockCopy(second, 0, result, first.Length, second.Length);
return result;
}
public string encryptAndEncodeToBase64(string data)
{
try
{
// Encrypt the JSON string
byte[] encryptedData = encryptInChunksUsingPrivateKey(Encoding.UTF8.GetBytes(data));
// Return the encrypted data encoded in Base64
return Convert.ToBase64String(encryptedData);
}
catch (Exception ex)
{
throw new Exception("Error in encryptAndEncodeToBase64: " + ex.Message, ex);
}
}
// Decode base64 and decrypt the data back to original object using public key
public string decodeAndDecryptFromBase64(string base64Data)
{
try
{
// Decode the Base64 to get the encrypted data
byte[] encryptedData = Convert.FromBase64String(base64Data);
// Decrypt the data
byte[] decryptedData = decryptInChunksUsingPublicKey(encryptedData);
// Convert decrypted byte array back to string
return Encoding.UTF8.GetString(decryptedData);
}
catch (Exception ex)
{
throw new Exception("Error in decodeAndDecryptFromBase64: " + ex.Message, ex);
}
}
public string encryptAndEncodeToBase64PublicKey(string data)
{
try
{
// Encrypt the JSON string
byte[] encryptedData = encryptInChunksUsingPublicKey(Encoding.UTF8.GetBytes(data));
// Return the encrypted data encoded in Base64
return Convert.ToBase64String(encryptedData);
}
catch (Exception ex)
{
throw new Exception("Error in encryptAndEncodeToBase64PublicKey: " + ex.Message, ex);
}
}
// Decode base64 and decrypt the data back to original object using private key
public string decodeAndDecryptFromBase64PrivateKey(string base64Data)
{
try
{
// Decode the Base64 to get the encrypted data
byte[] encryptedData = Convert.FromBase64String(base64Data);
// Decrypt the data
byte[] decryptedData = decryptInChunksUsingPrivateKey(encryptedData);
// Convert decrypted byte array back to string
return Encoding.UTF8.GetString(decryptedData);
}
catch (Exception ex)
{
throw new Exception("Error in decodeAndDecryptFromBase64PrivateKey: " + ex.Message, ex);
}
}
// Method to encrypt data in chunks using OAEP padding with public key
public byte[] encryptInChunksUsingPublicKey(byte[] data)
{
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest());
// In Java code the public key is used for encryption here.
cipher.Init(true, publicKey);
int dataLength = data.Length;
byte[] encryptedData = new byte[0];
// Encrypt in chunks
for (int i = 0; i < dataLength; i += MAX_RSA_BLOCK_SIZE)
{
int end = Math.Min(i + MAX_RSA_BLOCK_SIZE, dataLength);
byte[] chunk = new byte[end - i];
Array.Copy(data, i, chunk, 0, end - i);
byte[] encryptedChunk = cipher.ProcessBlock(chunk, 0, chunk.Length);
encryptedData = combineArrays(encryptedData, encryptedChunk);
}
return encryptedData;
}
// Method to decrypt data in chunks using private key
public byte[] decryptInChunksUsingPrivateKey(byte[] encryptedData)
{
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest());
cipher.Init(false, privateKey);
int encryptedDataLength = encryptedData.Length;
byte[] decryptedData = new byte[0];
// Decrypt in chunks (each chunk can be at most MAX_DE_RSA_BLOCK_SIZE bytes)
for (int i = 0; i < encryptedDataLength; i += MAX_DE_RSA_BLOCK_SIZE)
{
int end = Math.Min(i + MAX_DE_RSA_BLOCK_SIZE, encryptedDataLength);
byte[] chunk = new byte[end - i];
Array.Copy(encryptedData, i, chunk, 0, end - i);
// Decrypt the chunk
byte[] decryptedChunk = cipher.ProcessBlock(chunk, 0, chunk.Length);
decryptedData = combineDecodeArrays(decryptedData, decryptedChunk);
}
return decryptedData;
}
}
// Implementation of IPasswordFinder used for PEM decryption
public class MyPasswordFinder : IPasswordFinder
{
private readonly char[] password;
public MyPasswordFinder(string pass)
{
password = pass.ToCharArray();
}
public char[] GetPassword()
{
return (char[])password.Clone();
}
}
}
< /code>
Проверьте, и если есть какие -либо проблемы, пожалуйста, исправьте,
Когда мы конвертируем с помощью этого кода с помощью закрытого ключа, мы получаем HR Ошибка упоминания < /p>
Подробнее здесь: https://stackoverflow.com/questions/795 ... decryption
Когда мы преобразуем код Java в C# код, для шифрования и дешифрования. Мы получаем ошибку «Неверное текстовое исключение ⇐ JAVA
Программисты JAVA общаются здесь
1745829855
Anonymous
Когда мы пытаемся расшифровать ответ (зашифрованные данные), с нашим закрытым ключом мы получаем ошибку:-< /p>
Исключение текста цифера. преобразовать это < /p>
package com.sso.encryption;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import java.util.Arrays;
import java.util.Base64;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
public class RSAEncryptionWithAES256 {
PublicKey publicKey = null;
PrivateKey privateKey = null;
private static final int MAX_DE_RSA_BLOCK_SIZE = 256;
private static final int MAX_RSA_BLOCK_SIZE = 190;
public RSAEncryptionWithAES256() throws Exception {
// Add BouncyCastle provider (needed for OAEPWithSHA-256)
Security.addProvider(new BouncyCastleProvider());
// Load Public and Private Key from PEM files (with AES-256 encrypted private key)
publicKey = loadPublicKey("enc1_public_key.pem");
privateKey = loadEncryptedPrivateKey("enc2_private_key.pem");
}
public static void main(String[] args) throws Exception {
String req ="{\r\n"
+ " \"CorporateId\": \"40682399\",\r\n"
+ " ]\r\n"
+ "}";
RSAEncryptionWithAES256 rsaEncryptionWithAES256 = new RSAEncryptionWithAES256();
String encryptAndEncodeToBase64 = rsaEncryptionWithAES256.encryptAndEncodeToBase64(req);
System.out.println("Non Reverse: "+encryptAndEncodeToBase64);
String decryptedMessage = rsaEncryptionWithAES256.decodeAndDecryptFromBase64(encryptAndEncodeToBase64);
// String decryptedMsg = new String(decryptedMessage);
System.out.println("Non Reverse : "+decryptedMessage);
String encryptAndEncodeToBase64PublicKey = rsaEncryptionWithAES256.encryptAndEncodeToBase64PublicKey(decryptedMessage);
System.out.println("Reverse: "+encryptAndEncodeToBase64PublicKey);
String decodeAndDecryptFromBase64PrivateKey = rsaEncryptionWithAES256.decodeAndDecryptFromBase64PrivateKey(encryptAndEncodeToBase64PublicKey);
System.out.println("Reverse Rep : "+decodeAndDecryptFromBase64PrivateKey);
}
// Method to load the Public Key from a PEM file
public static PublicKey loadPublicKey(String filename) throws Exception {
FileInputStream fis = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
StringBuilder pemContent = new StringBuilder();
while ((line = br.readLine()) != null) {
if (!line.startsWith("-----")) {
pemContent.append(line);
}
}
byte[] encoded = Base64.getDecoder().decode(pemContent.toString());
X509EncodedKeySpec spec = new X509EncodedKeySpec(encoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(spec);
}
// Method to load the Private Key from a PEM file (with passphrase for AES-256 decryption)
public static PrivateKey loadEncryptedPrivateKey(String filename) throws Exception {
// Load the encrypted private key PEM file
FileReader pemFileReader = new FileReader(filename);
PEMParser pemParser = new PEMParser(pemFileReader);
// Read the encrypted private key info
PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemParser.readObject();
pemParser.close();
// Create the decryptor provider using a password (this should match the password used to encrypt the key) & add you pass phrase
char[] password = "demo".toCharArray();
JceOpenSSLPKCS8DecryptorProviderBuilder decryptorProviderBuilder = new JceOpenSSLPKCS8DecryptorProviderBuilder();
InputDecryptorProvider decryptorProvider = decryptorProviderBuilder.build(password);
// Decrypt the private key
PrivateKeyInfo privateKey = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decryptorProvider);
// To use this key with Java's standard APIs (for example, signing), you can convert it like this:
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// If you need to convert to a standard PrivateKey format, you can create the PKCS8EncodedKeySpec
byte[] encodedKey = privateKey.getEncoded();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
PrivateKey standardPrivateKey = keyFactory.generatePrivate(keySpec);
System.out.println("Standard Java Private Key: " + standardPrivateKey);
return standardPrivateKey;
}
// Method to encrypt data in chunks using OAEP padding
public byte[] encryptInChunksUsingPrivateKey(byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
int dataLength = data.length;
byte[] encryptedData = new byte[0];
// Encrypt in chunks
for (int i = 0; i < dataLength; i += MAX_RSA_BLOCK_SIZE) {
int end = Math.min(i + MAX_RSA_BLOCK_SIZE, dataLength);
byte[] chunk = Arrays.copyOfRange(data, i, end);
byte[] encryptedChunk = cipher.doFinal(chunk);
encryptedData = combineArrays(encryptedData, encryptedChunk);
}
return encryptedData;
}
// Method to decrypt data in chunks
public byte[] decryptInChunksUsingPublicKey(byte[] encryptedData) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
int encryptedDataLength = encryptedData.length;
byte[] decryptedData = new byte[0];
// Decrypt in chunks (each chunk can be at most MAX_RSA_BLOCK_SIZE bytes)
for (int i = 0; i < encryptedDataLength; i += MAX_DE_RSA_BLOCK_SIZE) {
int end = Math.min(i + MAX_DE_RSA_BLOCK_SIZE, encryptedDataLength);
byte[] chunk = Arrays.copyOfRange(encryptedData, i, end);
// Decrypt the chunk
byte[] decryptedChunk = cipher.doFinal(chunk);
decryptedData = combineDecodeArrays(decryptedData, decryptedChunk);
}
return decryptedData;
}
// Method to combine arrays
private byte[] combineDecodeArrays(byte[] first, byte[] second) {
byte[] result = new byte[first.length + second.length];
System.arraycopy(first, 0, result, 0, first.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
// Method to combine arrays
private byte[] combineArrays(byte[] first, byte[] second) {
byte[] result = new byte[first.length + second.length];
System.arraycopy(first, 0, result, 0, first.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public String encryptAndEncodeToBase64(String data) throws Exception {
// Encrypt the JSON string
byte[] encryptedData = encryptInChunksUsingPrivateKey(data.getBytes());
// Return the encrypted data encoded in Base64
return Base64.getEncoder().encodeToString(encryptedData);
}
// Decode base64 and decrypt the data back to original object
public String decodeAndDecryptFromBase64(String base64Data) throws Exception {
// Decode the Base64 to get the encrypted data
byte[] encryptedData = Base64.getDecoder().decode(base64Data);
// Decrypt the data
byte[] decryptedData = decryptInChunksUsingPublicKey(encryptedData);
// Convert decrypted byte array back to string
return new String(decryptedData);
}
public String encryptAndEncodeToBase64PublicKey(String data) throws Exception {
// Encrypt the JSON string
byte[] encryptedData = encryptInChunksUsingPublicKey(data.getBytes());
// Return the encrypted data encoded in Base64
return Base64.getEncoder().encodeToString(encryptedData);
}
// Decode base64 and decrypt the data back to original object
public String decodeAndDecryptFromBase64PrivateKey(String base64Data) throws Exception {
// Decode the Base64 to get the encrypted data
byte[] encryptedData = Base64.getDecoder().decode(base64Data);
// Decrypt the data
byte[] decryptedData = decryptInChunksUsingPrivateKey(encryptedData);
// Convert decrypted byte array back to string
return new String(decryptedData);
}
// Method to encrypt data in chunks using OAEP padding
public byte[] encryptInChunksUsingPublicKey(byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
// cipher.init(Cipher.ENCRYPT_MODE, privateKey);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int dataLength = data.length;
byte[] encryptedData = new byte[0];
// Encrypt in chunks
for (int i = 0; i < dataLength; i += MAX_RSA_BLOCK_SIZE) {
int end = Math.min(i + MAX_RSA_BLOCK_SIZE, dataLength);
byte[] chunk = Arrays.copyOfRange(data, i, end);
byte[] encryptedChunk = cipher.doFinal(chunk);
encryptedData = combineArrays(encryptedData, encryptedChunk);
}
return encryptedData;
}
// Method to decrypt data in chunks
public byte[] decryptInChunksUsingPrivateKey(byte[] encryptedData) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int encryptedDataLength = encryptedData.length;
byte[] decryptedData = new byte[0];
// Decrypt in chunks (each chunk can be at most MAX_RSA_BLOCK_SIZE bytes)
for (int i = 0; i < encryptedDataLength; i += MAX_DE_RSA_BLOCK_SIZE) {
int end = Math.min(i + MAX_DE_RSA_BLOCK_SIZE, encryptedDataLength);
byte[] chunk = Arrays.copyOfRange(encryptedData, i, end);
// Decrypt the chunk
byte[] decryptedChunk = cipher.doFinal(chunk);
decryptedData = combineDecodeArrays(decryptedData, decryptedChunk);
}
return decryptedData;
}
}
< /code>
и преобразованный код C# - < /p>
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Asn1.Pkcs;
namespace com.sso.encryption
{
public class RSAEncryptionWithAES256
{
public AsymmetricKeyParameter publicKey = null;
public AsymmetricKeyParameter privateKey = null;
private static readonly int MAX_DE_RSA_BLOCK_SIZE = 256;
private static readonly int MAX_RSA_BLOCK_SIZE = 190;
public RSAEncryptionWithAES256()
{
try
{
// Add BouncyCastle provider (needed for OAEPWithSHA-256)
// In .NET, BouncyCastle is used via its API, no need to add as provider.
// Load Public and Private Key from PEM files (with AES-256 encrypted private key)
publicKey = loadPublicKey("enc1_public_key.pem");
privateKey = loadEncryptedPrivateKey("enc2_private_key.pem");
}
catch (Exception ex)
{
throw new Exception("Error in constructor: " + ex.Message, ex);
}
}
public static void Main(string[] args)
{
try
{
string req = "{\r\n"
+ "}";
RSAEncryptionWithAES256 rsaEncryptionWithAES256 = new RSAEncryptionWithAES256();
string encryptAndEncodeToBase64 = rsaEncryptionWithAES256.encryptAndEncodeToBase64(req);
Console.WriteLine("Non Reverse: " + encryptAndEncodeToBase64);
string decryptedMessage = rsaEncryptionWithAES256.decodeAndDecryptFromBase64(encryptAndEncodeToBase64);
// string decryptedMsg = new string(decryptedMessage);
Console.WriteLine("Non Reverse : " + decryptedMessage);
string encryptAndEncodeToBase64PublicKey = rsaEncryptionWithAES256.encryptAndEncodeToBase64PublicKey(decryptedMessage);
Console.WriteLine("Reverse: " + encryptAndEncodeToBase64PublicKey);
string decodeAndDecryptFromBase64PrivateKey = rsaEncryptionWithAES256.decodeAndDecryptFromBase64PrivateKey(encryptAndEncodeToBase64PublicKey);
Console.WriteLine("Reverse Rep : " + decodeAndDecryptFromBase64PrivateKey);
}
catch (Exception ex)
{
Console.WriteLine("Exception in Main: " + ex.Message);
}
}
// Method to load the Public Key from a PEM file
public static AsymmetricKeyParameter loadPublicKey(string filename)
{
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
{
StringBuilder pemContent = new StringBuilder();
string line;
while ((line = sr.ReadLine()) != null)
{
if (!line.StartsWith("-----"))
{
pemContent.Append(line);
}
}
byte[] encoded = Convert.FromBase64String(pemContent.ToString());
return PublicKeyFactory.CreateKey(encoded);
}
}
// Method to load the Private Key from a PEM file (with passphrase for AES-256 decryption)
public static AsymmetricKeyParameter loadEncryptedPrivateKey(string filename)
{
using (StreamReader sr = new StreamReader(filename))
{
// Create the PEM reader with a password finder using the passphrase "demo"
PemReader pemReader = new PemReader(sr, new MyPasswordFinder("demo"));
object keyObject = pemReader.ReadObject();
pemReader.Reader.Close();
AsymmetricKeyParameter privateKeyParam = null;
if (keyObject is AsymmetricCipherKeyPair)
{
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)keyObject;
privateKeyParam = keyPair.Private;
}
else if (keyObject is AsymmetricKeyParameter)
{
privateKeyParam = (AsymmetricKeyParameter)keyObject;
}
else if (keyObject is Pkcs8EncryptedPrivateKeyInfo)
{
// If the object is of type Pkcs8EncryptedPrivateKeyInfo, decrypt it using the password.
Pkcs8EncryptedPrivateKeyInfo encInfo = (Pkcs8EncryptedPrivateKeyInfo)keyObject;
PrivateKeyInfo pkInfo = encInfo.DecryptPrivateKeyInfo(new MyPasswordFinder("demo"));
privateKeyParam = PrivateKeyFactory.CreateKey(pkInfo);
}
Console.WriteLine("Standard .NET Private Key: " + privateKeyParam.ToString());
return privateKeyParam;
}
}
// Method to encrypt data in chunks using OAEP padding with private key
public byte[] encryptInChunksUsingPrivateKey(byte[] data)
{
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest());
cipher.Init(true, privateKey);
int dataLength = data.Length;
byte[] encryptedData = new byte[0];
// Encrypt in chunks
for (int i = 0; i < dataLength; i += MAX_RSA_BLOCK_SIZE)
{
int end = Math.Min(i + MAX_RSA_BLOCK_SIZE, dataLength);
byte[] chunk = new byte[end - i];
Array.Copy(data, i, chunk, 0, end - i);
byte[] encryptedChunk = cipher.ProcessBlock(chunk, 0, chunk.Length);
encryptedData = combineArrays(encryptedData, encryptedChunk);
}
return encryptedData;
}
// Method to decrypt data in chunks using public key
public byte[] decryptInChunksUsingPublicKey(byte[] encryptedData)
{
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest());
cipher.Init(false, publicKey);
int encryptedDataLength = encryptedData.Length;
byte[] decryptedData = new byte[0];
// Decrypt in chunks (each chunk can be at most MAX_DE_RSA_BLOCK_SIZE bytes)
for (int i = 0; i < encryptedDataLength; i += MAX_DE_RSA_BLOCK_SIZE)
{
int end = Math.Min(i + MAX_DE_RSA_BLOCK_SIZE, encryptedDataLength);
byte[] chunk = new byte[end - i];
Array.Copy(encryptedData, i, chunk, 0, end - i);
// Decrypt the chunk
byte[] decryptedChunk = cipher.ProcessBlock(chunk, 0, chunk.Length);
decryptedData = combineDecodeArrays(decryptedData, decryptedChunk);
}
return decryptedData;
}
// Method to combine arrays
private byte[] combineDecodeArrays(byte[] first, byte[] second)
{
byte[] result = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, result, 0, first.Length);
Buffer.BlockCopy(second, 0, result, first.Length, second.Length);
return result;
}
// Method to combine arrays
private byte[] combineArrays(byte[] first, byte[] second)
{
byte[] result = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, result, 0, first.Length);
Buffer.BlockCopy(second, 0, result, first.Length, second.Length);
return result;
}
public string encryptAndEncodeToBase64(string data)
{
try
{
// Encrypt the JSON string
byte[] encryptedData = encryptInChunksUsingPrivateKey(Encoding.UTF8.GetBytes(data));
// Return the encrypted data encoded in Base64
return Convert.ToBase64String(encryptedData);
}
catch (Exception ex)
{
throw new Exception("Error in encryptAndEncodeToBase64: " + ex.Message, ex);
}
}
// Decode base64 and decrypt the data back to original object using public key
public string decodeAndDecryptFromBase64(string base64Data)
{
try
{
// Decode the Base64 to get the encrypted data
byte[] encryptedData = Convert.FromBase64String(base64Data);
// Decrypt the data
byte[] decryptedData = decryptInChunksUsingPublicKey(encryptedData);
// Convert decrypted byte array back to string
return Encoding.UTF8.GetString(decryptedData);
}
catch (Exception ex)
{
throw new Exception("Error in decodeAndDecryptFromBase64: " + ex.Message, ex);
}
}
public string encryptAndEncodeToBase64PublicKey(string data)
{
try
{
// Encrypt the JSON string
byte[] encryptedData = encryptInChunksUsingPublicKey(Encoding.UTF8.GetBytes(data));
// Return the encrypted data encoded in Base64
return Convert.ToBase64String(encryptedData);
}
catch (Exception ex)
{
throw new Exception("Error in encryptAndEncodeToBase64PublicKey: " + ex.Message, ex);
}
}
// Decode base64 and decrypt the data back to original object using private key
public string decodeAndDecryptFromBase64PrivateKey(string base64Data)
{
try
{
// Decode the Base64 to get the encrypted data
byte[] encryptedData = Convert.FromBase64String(base64Data);
// Decrypt the data
byte[] decryptedData = decryptInChunksUsingPrivateKey(encryptedData);
// Convert decrypted byte array back to string
return Encoding.UTF8.GetString(decryptedData);
}
catch (Exception ex)
{
throw new Exception("Error in decodeAndDecryptFromBase64PrivateKey: " + ex.Message, ex);
}
}
// Method to encrypt data in chunks using OAEP padding with public key
public byte[] encryptInChunksUsingPublicKey(byte[] data)
{
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest());
// In Java code the public key is used for encryption here.
cipher.Init(true, publicKey);
int dataLength = data.Length;
byte[] encryptedData = new byte[0];
// Encrypt in chunks
for (int i = 0; i < dataLength; i += MAX_RSA_BLOCK_SIZE)
{
int end = Math.Min(i + MAX_RSA_BLOCK_SIZE, dataLength);
byte[] chunk = new byte[end - i];
Array.Copy(data, i, chunk, 0, end - i);
byte[] encryptedChunk = cipher.ProcessBlock(chunk, 0, chunk.Length);
encryptedData = combineArrays(encryptedData, encryptedChunk);
}
return encryptedData;
}
// Method to decrypt data in chunks using private key
public byte[] decryptInChunksUsingPrivateKey(byte[] encryptedData)
{
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest());
cipher.Init(false, privateKey);
int encryptedDataLength = encryptedData.Length;
byte[] decryptedData = new byte[0];
// Decrypt in chunks (each chunk can be at most MAX_DE_RSA_BLOCK_SIZE bytes)
for (int i = 0; i < encryptedDataLength; i += MAX_DE_RSA_BLOCK_SIZE)
{
int end = Math.Min(i + MAX_DE_RSA_BLOCK_SIZE, encryptedDataLength);
byte[] chunk = new byte[end - i];
Array.Copy(encryptedData, i, chunk, 0, end - i);
// Decrypt the chunk
byte[] decryptedChunk = cipher.ProcessBlock(chunk, 0, chunk.Length);
decryptedData = combineDecodeArrays(decryptedData, decryptedChunk);
}
return decryptedData;
}
}
// Implementation of IPasswordFinder used for PEM decryption
public class MyPasswordFinder : IPasswordFinder
{
private readonly char[] password;
public MyPasswordFinder(string pass)
{
password = pass.ToCharArray();
}
public char[] GetPassword()
{
return (char[])password.Clone();
}
}
}
< /code>
Проверьте, и если есть какие -либо проблемы, пожалуйста, исправьте,
Когда мы конвертируем с помощью этого кода с помощью закрытого ключа, мы получаем HR Ошибка упоминания < /p>
Подробнее здесь: [url]https://stackoverflow.com/questions/79595912/when-we-converts-the-java-code-to-c-sharp-code-for-encryption-and-decryption[/url]
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Когда мы преобразуем код Java в C# код, для шифрования и дешифрования. Мы получаем ошибку «Неверное текстовое исключение
Anonymous » » в форуме C#Когда мы пытаемся расшифровать ответ (зашифрованные данные), с нашим закрытым ключом мы получаем ошибку:-
Исключение текста цифера. преобразовать это
package com.sso.encryption;
import java.io.*;
import java.security.*;
import javax.crypto.*;... - 0 Ответы
- 10 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Какое исключение мы получаем от SQL Server и драйвера jdbc Sybase точно так же, как мы получаем для драйвера Oracle JDBC
Anonymous » » в форуме JAVAУ меня есть приложение Spring Boot, в котором я подключаюсь к базам данных SQL Server, Sybase, Oracle и MySQL, чтобы получить подробную информацию о метаданных. При сборе количества строк в таблицах с приведенным ниже кодом в Oracle... - 0 Ответы
- 28 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Какое исключение мы получаем от SQL Server и драйвера jdbc Sybase, точно так же, как мы получаем для драйвера Oracle JDB
Anonymous » » в форуме JAVAУ меня есть приложение Spring Boot, в котором я подключаюсь к базам данных SQL Server, Sybase, Oracle и MySQL, чтобы получить подробную информацию о метаданных. При сборе количества строк в таблицах с приведенным ниже кодом в Oracle... - 0 Ответы
- 27 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Код шифрования/дешифрования пароля в .NET
Anonymous » » в форуме C#Мне нужно простое шифрование и расшифровка пароля на C#. Как сохранить пароль в зашифрованном виде в базе данных и получить его в исходном формате путем расшифровки?
Подробнее здесь: - 0 Ответы
- 18 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Android 4.2 сломал мой код шифрования/дешифрования AES
Anonymous » » в форуме AndroidЯ впервые обращаюсь сюда за помощью, мой отдел (правительство) опубликовал какое-то приложение на рынке (Google Play), и шифрование и описание работали очень хорошо до вчерашнего дня, когда я получил Jelly Bean. 4.2 на моем Нексусе.
Шифрование... - 0 Ответы
- 16 Просмотры
-
Последнее сообщение Anonymous
-
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...