Статус: Новичок
Группы: Участники
Зарегистрирован: 24.10.2019(UTC) Сообщений: 2  Откуда: Вологда Поблагодарили: 1 раз в 1 постах
|
Добрый день. Просьба помочь разобраться с ошибкой. Пытаюсь расшифровать идентификатор сессии зашифрованный в соответствии с ГОСТ 28147-89. Сборка JCP 2019-10-24 11:03:53.762 INFO 7900 --- [ task-pool-1] ru.CryptoPro.JCP.tools.JCPLogger : Loading JCP 2.0.40424 2019-10-24 11:03:53.791 INFO 7900 --- [ task-pool-1] ru.CryptoPro.JCP.tools.JCPLogger : JCP loaded. При расшифровке выходит ошибка. Код:java.exe : java.security.InvalidKeyException: Wrapped key is invalid
Сообщение для расшифровки во вложении (ciphertext).  24.10.2019 09_38_00.rar (1kb) загружен 4 раз(а).Код:
public byte[] decrypt(byte[] ciphertext, PrivateKey recipientPrivateKey) throws Exception
{
//разбор CMS-сообщения
Asn1BerDecodeBuffer dbuf = new Asn1BerDecodeBuffer(ciphertext);
final ContentInfo all = new ContentInfo();
all.decode(dbuf);
dbuf.reset();
final EnvelopedData cms = (EnvelopedData) all.content;
RecipientInfo[] recipientInfos = cms.recipientInfos.elements;
KeyTransRecipientInfo keytrans = new KeyTransRecipientInfo();
if (recipientInfos[0].getChoiceID() == RecipientInfo._KTRI) {
keytrans = (KeyTransRecipientInfo) (recipientInfos[0].getElement());
} else {
LOG.warn("RecipientInfo type unsupported. KeyTransRecipientInfo (ktri) supported only. RecipientInfo type is " + cms.recipientInfos.elements[0].getElemName());
return null;
}
// разбор параметров ключа
final Asn1BerEncodeBuffer ebuf = new Asn1BerEncodeBuffer();
dbuf = new Asn1BerDecodeBuffer(keytrans.encryptedKey.value);
final GostR3410_KeyTransport encrKey = new GostR3410_KeyTransport();
encrKey.decode(dbuf);
dbuf.reset();
// sessionEncryptedKey
encrKey.sessionEncryptedKey.encode(ebuf);
final byte[] wrapKey = ebuf.getMsgCopy();
ebuf.reset();
// ephemeralPublicKey
encrKey.transportParameters.ephemeralPublicKey.encode(ebuf);
final byte[] encodedPub = ebuf.getMsgCopy();
ebuf.reset();
final byte[] sv = encrKey.transportParameters.ukm.value;
final Gost28147_89_Parameters params = (Gost28147_89_Parameters) cms.encryptedContentInfo.contentEncryptionAlgorithm.parameters;
final byte[] iv = params.iv.value;
final OID cipherOID = new OID(params.encryptionParamSet.value);
LOG.info(cipherOID.toString());
// зашифрованная нагрузка
final byte[] encryptedData = cms.encryptedContentInfo.encryptedContent.value;
//отправитель - открытый ключ из cms
final X509EncodedKeySpec pspec = new X509EncodedKeySpec(encodedPub);
//final KeyFactory kf = KeyFactory.getInstance(JCP.GOST_EL_DH_NAME );
final KeyFactory kf = KeyFactory.getInstance(JCP.GOST_DH_2012_256_NAME, "JCP");
final PublicKey senderPublicKey = kf.generatePublic(pspec);
BigInteger serialNumber=null;
// Идентификация получателя
if (keytrans.rid.getChoiceID() == RecipientIdentifier._ISSUERANDSERIALNUMBER)
{
IssuerAndSerialNumber issuerAndSerialNumber = (IssuerAndSerialNumber) keytrans.rid.getElement();
serialNumber = issuerAndSerialNumber.serialNumber.value;
LOG.info(String.valueOf(serialNumber));
}
LOG.info(recipientPrivateKey.getAlgorithm());
LOG.info(recipientPrivateKey.toString());
if (recipientPrivateKey == null)
{
if (LOG.isWarnEnabled())
{
LOG.warn("Ключ не найден '" + serialNumber + "'.");
}
return null;
}
// выработка ключа согласования получателем
//final KeyAgreement responderKeyAgree = KeyAgreement.getInstance(JCP.GOST_EL_DH_NAME );
final KeyAgreement responderKeyAgree = KeyAgreement.getInstance(JCP.GOST_DH_2012_256_NAME, CryptoProvider.PROVIDER_NAME);
responderKeyAgree.init(recipientPrivateKey, new IvParameterSpec(sv), null);
responderKeyAgree.doPhase(senderPublicKey, true);
final SecretKey agreemtntKey = responderKeyAgree.generateSecret("GOST28147");
// Расшифрование симметричного ключа.
//final Cipher cipher = Cipher.getInstance(CIPHER_MODE);
final Cipher cipher = Cipher.getInstance("GOST28147/CFB/NoPadding", CryptoProvider.PROVIDER_NAME);
cipher.init(Cipher.UNWRAP_MODE, agreemtntKey, (SecureRandom) null);
final SecretKey simmKey = (SecretKey) cipher.unwrap(wrapKey, null, Cipher.SECRET_KEY);
// Расшифрование текста на симметричном ключе.
final GostCipherSpec spec = new GostCipherSpec(iv, cipherOID);
cipher.init(Cipher.DECRYPT_MODE, simmKey, spec, null);
byte[] result = cipher.doFinal(encryptedData, 0, encryptedData.length);
return result;
}
Отредактировано пользователем 24 октября 2019 г. 13:25:20(UTC)
| Причина: Не указана
|
|
|
|
Статус: Сотрудник
Группы: Участники
Зарегистрирован: 06.12.2008(UTC) Сообщений: 4,006  Откуда: Крипто-Про Сказал(а) «Спасибо»: 21 раз Поблагодарили: 715 раз в 675 постах
|
Здравствуйте. Без закрытого ключа не расшифровать пример. В keyTransport.transportParameters.encryptionParamSet.value что? OID oid = new OID(keyTransport.transportParameters.encryptionParamSet.value);
|
|
|
|
|
Статус: Новичок
Группы: Участники
Зарегистрирован: 24.10.2019(UTC) Сообщений: 2  Откуда: Вологда Поблагодарили: 1 раз в 1 постах
|
Добрый день. Поискал по форуму. Помогло решение через EnvelopedSignature CAdES. Все отлично расшифровал. Код:
public static byte[] DecryptSessionID(byte[] encoded, PrivateKey privateKey, X509Certificate cert) throws Exception
{
EnvelopedSignature signature = new EnvelopedSignature(new ByteArrayInputStream(encoded));
ByteArrayOutputStream decryptedByteDataStream = new ByteArrayOutputStream();
signature.decrypt(cert, privateKey, decryptedByteDataStream);
byte[] decryptedData = decryptedByteDataStream.toByteArray();
decryptedByteDataStream.flush();
decryptedByteDataStream.close();
return decryptedData;
}
|
 1 пользователь поблагодарил panad-maxi за этот пост.
|
|
|
Быстрый переход
Вы не можете создавать новые темы в этом форуме.
Вы не можете отвечать в этом форуме.
Вы не можете удалять Ваши сообщения в этом форуме.
Вы не можете редактировать Ваши сообщения в этом форуме.
Вы не можете создавать опросы в этом форуме.
Вы не можете голосовать в этом форуме.
Important Information:
The Форум КриптоПро uses cookies. By continuing to browse this site, you are agreeing to our use of cookies.
More Details
Close