Я использую следующий код для шифрования данных и хочу извлечь зашифрованный ключ и содержимое отдельно.
Код шифрования:
"
Шифрование общедоступного класса {
Код: Выделить всё
static String certificatePath = "C:\\Users\\PSAD07564\\Desktop\\Peppol\\IVLenght\\peppol.lx.erf01.net.crt";
private static final String RSA_TRANSFORMATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
private static final String AES_TRANSFORMATION = "AES/GCM/NoPadding";
private static final int GCM_TAG_LENGTH = 128;
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
// Path to the .key file
String keyFilePath = "C:\\Users\\PSAD07564\\Desktop\\Peppol\\IVLenght\\peppol.lx.erf01.net.key";
// Read the private key file
String keyContent = new String(Files.readAllBytes(Paths.get(keyFilePath)));
// Clean up the key content
keyContent = keyContent.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+", ""); // Remove all whitespace
// Decode the Base64-encoded private key
byte[] keyBytes = Base64.getDecoder().decode(keyContent);
// Generate a PrivateKey instance
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
String plainText = "AES 256 GCM Testing";
// Create a CertificateFactory instance
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
// Read the certificate from the file
FileInputStream fis = new FileInputStream(certificatePath);
X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(fis);
CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
CMSEnvelopedData data = null;
cmsEnvelopedDataGenerator.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(certificate, rsaesOaepIdentifier())
.setProvider(BouncyCastleProvider.PROVIDER_NAME));
data = cmsEnvelopedDataGenerator.generate(new CMSProcessableByteArray(plainText.getBytes()),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_GCM).setProvider("BC").build());
byte[] data1 = data.getEncoded();
System.out.println("Data:");
System.out.println(data);
System.out.println(data1);
}
private static AlgorithmIdentifier rsaesOaepIdentifier() {
AlgorithmIdentifier hash = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE);
AlgorithmIdentifier mask = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hash);
AlgorithmIdentifier pSource = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]));
return new AlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP, new RSAESOAEPparams(hash, mask, pSource));
}
"
Проблема:
Мне нужно извлечь зашифрованный ключ и зашифрованное содержимое из массива data1 байт (закодированный конверт CMS).
Может ли кто-нибудь подсказать мне, как извлечь эти компоненты (зашифрованный ключ и зашифрованный контент) отдельно от объекта CMSEnvelopedData, сгенерированного методом data.getEncoded()?
Будем очень признательны за любую помощь с примерами кода или предложениями!
Подробнее здесь: https://stackoverflow.com/questions/792 ... ddata-obje