Java security invalidkeyexception ioexception der input integer tag error

Here's the exception: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error at sun.security.rsa.RSAKeyFactory.engineGeneratePr...

Here’s the exception:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error
  at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source)
  at java.security.KeyFactory.generatePrivate(Unknown Source)

Caused by: java.security.InvalidKeyException: IOException : DER input, Integer tag error at sun.security.pkcs.PKCS8Key.decode(Unknown Source)

Here’s the code:

import java.io.*;
import java.security.*;
import java.security.KeyStore.PasswordProtection;
import java.security.cert.CertificateException;
import java.security.spec.*;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;

import org.bouncycastle.asn1.*;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.util.encoders.Base64;

public class KeyPairUtil {

final static String keyStoreFile = "D:\aeskey.jks";

private static final ASN1ObjectIdentifier AES = ASN1ObjectIdentifier.getInstance(NISTObjectIdentifiers.id_aes128_CBC);

public static void main(String[] args) throws Exception {

    final java.security.KeyPairGenerator gen = java.security.KeyPairGenerator.getInstance("RSA");
    gen.initialize(1024);
    final KeyPair keyPair = gen.generateKeyPair();
    wrapKeypairWithSymmetricKey(keyPair);
}

public static KeyPair wrapKeypairWithSymmetricKey(KeyPair keyPair) {

    try {
        PrivateKey priv = keyPair.getPrivate();
        SecretKey symmetricKey = getSymmetricKeyFromJKSFile();
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        final IvParameterSpec iv = new IvParameterSpec(new byte[16]);
        cipher.init(Cipher.WRAP_MODE, symmetricKey, iv);
        System.out.println(iv.getIV());
        ASN1Encodable params = new DEROctetString(iv.getIV());
        AlgorithmIdentifier algId = new AlgorithmIdentifier(AES, params);
        byte[] wrappedKey = cipher.wrap(priv);
        KeyFactory keyFactory = KeyFactory.getInstance(priv.getAlgorithm());
        byte[] pkcs8enc = new EncryptedPrivateKeyInfo(algId, wrappedKey).getEncoded();
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pkcs8enc);
        PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec); //throwing error in this line
        KeyPair keypair = new KeyPair(keyPair.getPublic(), privateKey2);
        return keypair;
    } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | NoSuchPaddingException | IllegalBlockSizeException | IOException | InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
    return null;
}

private static SecretKey getSymmetricKeyFromJKSFile() {

    String jkspassword = "password";
    PasswordProtection keyPassword = new PasswordProtection("keypassword".toCharArray());
    try {
        KeyStore keyStore = loadKeyStore(keyStoreFile, jkspassword);
        // retrieve the stored key back
        KeyStore.Entry entry = keyStore.getEntry("keyentry", keyPassword);
        SecretKey keyFound = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
        return keyFound;
    } catch (CertificateException | IOException | NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) {
        e.printStackTrace();
    }
    return null;
}

private static KeyStore loadKeyStore(String fileName, String jkspassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {

    File file = new File(fileName);
    final KeyStore keyStore = KeyStore.getInstance("JCEKS");
    if (file.exists()) {
        keyStore.load(new FileInputStream(file), jkspassword.toCharArray());
    }
    return keyStore;
}
}

I hope somebody knows how to solve?

Содержание

  1. java.security.InvalidKeyException – How to solve InvalidKeyException
  2. 1. A simple Encryption/Decryption Application
  3. 2. A simple example of InvalidKeyException
  4. 3. How to solve InvalidKeyException
  5. «algid parse error, not a sequence» on encrypt-config-value with RSA private key #13
  6. Comments
  7. case of «UnrecoverableKeyException: DER input, Integer tag error»?
  8. Unable to generate private key from password-protected private key
  9. Answers
  10. Шифрование с помощью закрытого ключа RSA в Java
  11. 5 ответов

java.security.InvalidKeyException – How to solve InvalidKeyException

Posted by: Nikos Maravitsas in InvalidKeyException July 31st, 2014 0 Views

In this example we are going to talk about java.security.InvalidKeyException . It is probably the most common exception you will stumble upon when handling encryption in your Java application. java.security.InvalidKeyException is a subclass of java.security.KeyException which in turn is a subclass of java.security.GeneralSecurityException .

As the name suggests, InvalidKeyException emerges when there is something wrong with the encryption key you are trying to use in one of your encryption algorithms. Most common problems with encryption keys include wrong length of the key, invalid encoding, and of course wrong initialization of the key (probably the key is NULL …).

To demonstrate this Exception we are going to create a simple application with a utility class that is able of performing AES encryption.

1. A simple Encryption/Decryption Application

The purpose of this example is not to dive deep in the AES encryption standard, nor to the implementation of this algorithm in Java. Nevertheless here is a simple utility class that can encrypt and decrypt a Java String , considered as the plaintext.

This class has to static utility methods :

  • encrypt: Takes the plain text and the encryprion key as input and produces the cipher text with UTF-8 encoding.
  • decrypt: Takes the cipher text and the encryprion key as input and produces the plain text with UTF-8 encoding.

The above class uses the AESUtils in order to encrypt and decrypt a String . Here is the output when you run it:

2. A simple example of InvalidKeyException

Now, by default JDK 1.7, can use AES 128-bit encryption, which means that the key has to be 128 bits long. Additionally the plain text has to be a multiple of 16 – that is why you see some null padding at the end of PLAIN_TEXT . So now, Let’s try to double the size of the encryption key to 256 bits. You can quickly do that :

Here is the output when you run it:

So by default the key size is not supported. This is the most common case of InvalidKeyException .

Another common case as well is when the encryption key is not a power of 2 (in most modern implementation the key should be at least 56 bits). For example:

Here is the output when you run it:

3. How to solve InvalidKeyException

The first thing you should do when you come up with this exception, is check if your encryption key is correctly initialized (not NULL ). Then make sure that its length in bits is a power of two. If you want to use a String as your encryption key you should check its length in bytes and multiply by 8 to find the length in bits. The safest way to do that is first to convert the String in a byte array and then check the array’s length. You should keep in mind that in most JVM 64-bit implementation each character in the String takes up 2 bytes.

After checking all the above you should make sure that your encryption engine supports key of that length. If you have to use 256-AES or more here is what you should do:

  1. Visit Oracle’s website and put ‘Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files’ on the search box. Here is the quick link with the results I’ve got : http://tinyurl.com/m65q5ax
  2. Then follow the link ‘Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 7 Download’
  3. Download UnlimitedJCEPolicyJDK7.zip
  4. Extract the folder. Inside you will find local_policy.jar and US_export_policy.jar .
  5. Go to your Java installation directory (aka JAVA_HOME) and find : JAVA_HOME/jre/lib/security . Paste these two files. Files with the same names will most probably be there already. You need to replace them with the new files.

That’s it. You can now restart your project and use 256-AES, 512-AES and so on.

Источник

«algid parse error, not a sequence» on encrypt-config-value with RSA private key #13

I wanted to encrypt a config value using the RSA algorithm.
I also wanted to «publish» the public key, and keep the private key private.

Generating RSA key:

Following your directions: «for encrypting values. In the case of non-symmetric algorithms (e.g. RSA) specify the private key»..

Encrypting a value using private key:

For the sake of experimentation, encrypting a value without referencing the private key explicitly succeeds:

. and the service can successfully decrypt the encrypted value in the config.yml.

However, this bundle seems to require that both, public and private, keys are found in var/conf directory.

The benefit of using an asymmetric algorithm like RSA would be allowing me to publish the public key and keep the private key private. I tried moving the private key from var/conf directory and leaving just the public key there and got this error:

Am I missing something obvious here?
Thanks

The text was updated successfully, but these errors were encountered:

To the first point — I made a mistake in the readme, sorry — will push a fix. The public key is used for encryption (producing the encrypted values), the private key for decryption (reading the encrypted values from the config and decrypting them for the app to use).

The readme should say «for encrypting values. In the case of non-symmetric algorithms (e.g. RSA) specify the public key»

For the second point, when running, the current code path assumes you have the public and private keys in var/conf, although only the private key is used.

An example use of the non-symmetric keys:

  1. Install your service on host1, generate the keypair (public and private)
  2. Transfer the public key to host2
  3. Install something giving you the encrypted-config-value cli on host2
  4. Use the cli to encrypt a config value, specifying the path to the public key
  5. Put that encrypted value into the config on host1 (manually/using some deploy script. )
  6. Run the service on host1, and it will decrypt the value (using the private key)

The rough intent here is that only the running service on host1 can read the encrypted values, yet we could produce the configuration files in some other place, as long as we have the public key.

Above you mention «I tried moving the private key from var/conf directory and leaving just the public key there and got this error:». Was this when running your actual dropwizard service or when running a command? From the stacktrace, it looks like the former — in which case, you’ll need to have a private key in order to be able to decrypt the value in the config file.

I think a potential enhancement here is to allow running the service without a public key present, since it’s kinda superfluous.

Hi Ben, thanks for looking into this, and great bundle!

The last exception occurred when I was launching the actual dw service with java -jar server config.yml as it was attempting to read the config.

It would be a great enhancement if only one key had to be available to the dw service at startup time. Otherwise, with both, public and private, keys present in one place, there is no real advantage to use RSA over AES.

Using Alice and Bob as a reference, Alice gives Bob her public key only, and Bob can now create an encrypted message with it. Alice will use her private key to read the encrypted message.

  1. An admin creates an encrypted value by running «encrypt-config-value» (which should ideally only require the public key) on host0 (his admin workstation).
  2. The dw service instance deployed on hostN should only require the private key to be present (in var/conf) in order to be able to decrypt the encrypted config value.

Semantically, you could also reverse the notions, but that’s in the eye of the beholder..

Currently this is what happens at dw service startup time when one or the other key is removed from var/conf:

private only — the code simply expects to find both:

public key only in var/conf — the public key cannot be used to decrypt the encrypted value:

Источник

case of «UnrecoverableKeyException: DER input, Integer tag error»?

  • use the [CODE] tags — it makes it much easier for people to help you.

  • after searching the net for hours, it turns out the problem is how the KeyStore is initialized. the java tutorial on the sun site says that the default provider should be fine, but it’s not.

    hope that saves someone some agony.
    Jon

    use the [CODE] tags — it makes it much easier for people to help you.

  • hope that saves someone some agony.
    Jon[/QB]

    GOD BLESS YOU JON.
    I can pass one further tip on for using keystores.
    Don’t try and create one manually the first time. It don’t work!
    I got this from somewhere else on the web — here is my function for creating keystores — it basically invokes the keystore tool and then picks up the output.
    You may have to edit it a little.
    Again, hope it helps someone, like Jon helped me 🙂

    IM
    (I edited the post to fix the typo involved in the code tags — JAM)
    [ August 25, 2003: Message edited by: Joel McNary ]

    Источник

    Unable to generate private key from password-protected private key

    I’ve been writing some code to sign data. So far this is what I have
    The problem is that I’m getting the following exception and I can’t find infomation about it.
    What does DER input, Integer tag error means? How can I read a password-protected PKCS8 DER private key to sign a file?

    Thanks so much in advance .

    Edited by: 879653 on 09-dic-2011 15:44

    Answers

    I was thinking the same. I don’t know how was it generated, the government is giving them so the people can pay their taxes over internet. In the page of the government it says that *»the private key is a file with .key extension as defined in the standard PKCS8 and is ciphered by the same specifications of standard PKCS1″*

    It uses RSA as algorithm, that’s 100% sure.

    I don’t know anything about the envelope so I can’t tell you if it has something like that.

    By the way, it has a password that protects the private key, doesn’t it has something to do with my problem? Just guessing.

    Finally, is there a way to know what format it is? I have the certificate that belongs to that key and I can read it with OpenSSL, I don’t know if that helps though.

    Thanks for answering.

    That scares me! This means that the government have access to your private key so it is not very private. Only you should have access to your private key; not your government, your cousin, your uncle, your lawyer or even your wife.

    It uses RSA as algorithm, that’s 100% sure.

    I don’t know anything about the envelope so I can’t tell you if it has something like that.

    Open the key file with a text editor. If it is a text file then it should have a header saying something like RSA PRIVATE KEY with a Base64 encoded body (the actual private key). If it is not a text file then I can’t help without access to it and it does not make security sense to give me access.

    Does the government also supply the password? If not then presumably they provide some software for you to use that has the password compiled into it.

    Источник

    Шифрование с помощью закрытого ключа RSA в Java

    Я пытаюсь зашифровать некоторый контент с помощью секретного ключа RSA.

    но превращая его в использование закрытых ключей, а не публичных. Следуя этому примеру, я думаю, что мне нужно сделать следующее:

    • Чтение в закрытом ключе формата DER
    • Создать PCKS8EncodedKeySpec
    • вызов generatePrivate() из KeyFactory для получения объекта закрытого ключа
    • Используйте этот объект закрытого ключа с объектом Cipher для шифрования

    Ключ был сгенерирован из openssl:

    openssl genrsa -aes256 -out private.pem 2048

    а затем преобразован в формат DER с помощью:

    openssl rsa -in private.pem -outform DER -out private.der

    Я генерирую PKCS8EncodedKeySpec с помощью:

    И затем сгенерируйте закрытый ключ с помощью:

    Однако при вызове:

    • Правильно ли подходит общий подход?
    • Используется ли PCKS8EncodedKeySpec правильный ключ?
    • Любые мысли о неверной ошибке спецификации ключа?

    5 ответов

    Прежде всего, я смущен, почему вы планируете использовать Cipher для шифрования с помощью закрытого ключа, а не для подписания с Signature . Я не уверен, что все поставщики RSA Cipher будут использовать правильный тип блока для настройки, но стоит попробовать.

    Отметив это, я думаю, что вы пытаетесь загрузить нестандартный ключ OpenSSL. Преобразование его в DER с помощью rsa — это просто декодирование с базой 64; структура ключа не является PKCS # 8.

    Вместо этого после genrsa используйте команду openssl pkcs8 для преобразования сгенерированного ключа в незашифрованный формат PKCS # 8, DER:

    Это приведет к созданию незашифрованного закрытого ключа, который может быть загружен с помощью PKCS8EncodedKeySpec .

    Вы не можете шифровать с помощью закрытого ключа. Если JCE позволяет вам это сделать, это просто случайно.

    Вам нужно использовать подпись. Вот фрагмент кода, чтобы сделать это,

    Не случайно, что шифрование с закрытым ключом разрешено. Если вы хотите разбить подпись на индивидуальное хеширование и шифрование, необходимо шифрование с помощью закрытого ключа. Допустим, у меня есть документ, который мне нужно подписать, а мой ключ находится в сети HSM. Теперь либо я передаю весь документ в HSM, чтобы подписать, либо я могу создать локальный хэш и передать его в HSM только для шифрования. Мой выбор будет зависеть от того, дает ли локальное вычисление хеша лучшую производительность, а именно: делегированное хэш-вычисление с задержкой сети.

    Этот вопрос довольно старый, но я недавно наткнулся на проблему (я выполняю требования к некоторому протоколу, который требует шифрования с закрытым ключом). Я просто напишу сообщение из forum:

    Недавно я наткнулся на ту же проблему, представив PMR 22265,49R и поддержку IBM после консультации с «разработкой» (кто бы это ни был), что частные ключи не могут использоваться для шифрования. Независимо от того, насколько я пытался спорить с ними, что частные ключи не должны использоваться для защиты данных, что является лишь одной из целей шифрования, и что совершенно нормально использовать закрытые ключи для шифрования для достижения отказа от отказа, они были непоколебимы в их вере. Вы должны любить людей, которые настаивают на том, что 2×2 = 5.

    Вот как я работал над этой проблемой: по сути, я создал объект открытого ключа с криптовым материалом с закрытым ключом. Вам нужно будет сделать обратное, создать объект закрытого ключа с криптовальным материалом с открытым ключом, чтобы расшифровать с помощью открытого ключа, если вы хотите, чтобы исключение «Открытый ключ не использовалось для дешифрования».

    Источник

    #java #encryption #elliptic-curve

    #Ява #шифрование #эллиптическая кривая

    Вопрос:

    Небольшой вопрос о том, как использовать закрытый ключ эллиптической кривой с java 11, пожалуйста.

    У меня есть эти команды:

     openssl pkcs12 -in file.p12 -out output.txt Enter Import Password: MAC verified OK Enter PEM pass phrase: Verifying - Enter PEM pass phrase:  

    затем я могу запустить cat на выходе:

     cat output.txt Bag Attributes  friendlyName:   localKeyID:  Key Attributes: lt;No Attributesgt; -----BEGIN ENCRYPTED PRIVATE KEY----- MI[...]0= -----END ENCRYPTED PRIVATE KEY----- Bag Attributes  friendlyName:   localKeyID:  subject=/CN= issuer=/CN= -----BEGIN CERTIFICATE----- MII[...]Z -----END CERTIFICATE-----  

    Обратите внимание, я использую […] для редактирования фактического содержимого.

    И я просто хочу использовать этот закрытый ключ, тот, что в -----BEGIN ENCRYPTED PRIVATE KEY----- -----END ENCRYPTED PRIVATE KEY----- блоке

    Поэтому я попробовал следующее: сначала я удалил ЗАШИФРОВАННЫЙ ЗАКРЫТЫЙ ключ BEGIN, разрывы строк, ЗАШИФРОВАННЫЙ ЗАКРЫТЫЙ КЛЮЧ END

     String privateKeyPEM = "MI[...]0="; //the same private key as above  byte[] keyData = Base64.getDecoder().decode(privateKeyPEM);  EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(keyData);  KeyFactory kf = KeyFactory.getInstance("EC");  PrivateKey privKey = kf.generatePrivate(privKeySpec);  

    Однако я получаю эту ошибку:

     aused by: java.security.InvalidKeyException: IOException : DER input, Integer tag error  at java.base/sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:350)  at java.base/sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:355)  at jdk.crypto.ec/sun.security.ec.ECPrivateKeyImpl.lt;initgt;(ECPrivateKeyImpl.java:74)  at jdk.crypto.ec/sun.security.ec.ECKeyFactory.implGeneratePrivate(ECKeyFactory.java:237)  at jdk.crypto.ec/sun.security.ec.ECKeyFactory.engineGeneratePrivate(ECKeyFactory.java:165)  

    Могу я спросить, в чем, пожалуйста, проблема? Кроме того, могу я спросить, как это исправить?

    Спасибо

    Ответ №1:

    Проблем нет, но ключ (EC), который вы пытаетесь прочитать, зашифрован — чистая Java не может считывать ключи такого рода.

    Вы можете написать много кода для анализа и расшифровки ключа или использовать Надувной замок, чтобы выполнить эту работу за вас.

    Добавьте эту строку в начало вашей программы:

     Security.addProvider(new BouncyCastleProvider());  

    затем используйте эту функцию, где строка s принимает зашифрованный ключ, включая строки «— Begin — / end:

     static public PrivateKey stringToPrivateKey(String s, String password)  throws IOException, PKCSException {  PrivateKeyInfo pki;  try (PEMParser pemParser = new PEMParser(new StringReader(s))) {  Object o = pemParser.readObject();  if (o instanceof PKCS8EncryptedPrivateKeyInfo) { // encrypted private key in pkcs8-format  System.out.println("key in pkcs8 encoding");  PKCS8EncryptedPrivateKeyInfo epki = (PKCS8EncryptedPrivateKeyInfo) o;  System.out.println("epki:"   epki.getEncryptionAlgorithm().getAlgorithm());  JcePKCSPBEInputDecryptorProviderBuilder builder =  new JcePKCSPBEInputDecryptorProviderBuilder().setProvider("BC");  InputDecryptorProvider idp = builder.build(password.toCharArray());  pki = epki.decryptPrivateKeyInfo(idp);  } else if (o instanceof PEMEncryptedKeyPair) { // encrypted private key in pkcs8-format  System.out.println("key in pkcs1 encoding");  PEMEncryptedKeyPair epki = (PEMEncryptedKeyPair) o;  PEMKeyPair pkp = epki.decryptKeyPair(new BcPEMDecryptorProvider(password.toCharArray()));  pki = pkp.getPrivateKeyInfo();  } else if (o instanceof PEMKeyPair) { // unencrypted private key  System.out.println("key unencrypted");  PEMKeyPair pkp = (PEMKeyPair) o;  pki = pkp.getPrivateKeyInfo();  } else {  throw new PKCSException("Invalid encrypted private key class: "   o.getClass().getName());  }  JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");  return converter.getPrivateKey(pki);  } }  

    Комментарии:

    1. Действительно, большое спасибо @Michael!

    If you have a public key in this form (and not within a certificate), I’d recommend using BouncyCastle’s PEMReader. Its readObject() method can read a lot for formats: public keys, certificates, private keys (although you may need to use the method with a password)…

    If you don’t want to use BouncyCastle, you can read certificates using a CertificateFactory (see examples). With a certificate in PEM format in an InputStream:

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(inputStream);
    

    For private keys, if your private key is a PKCS#8 structure in DER format, you can read it directly using PKCS8EncodedKeySpec. For example:

    KeyFactory kf = KeyFactory.getInstance("RSA");
    // Read privateKeyDerByteArray from DER file.
    KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyDerByteArray);
    PrivateKey key = kf.generatePrivate(keySpec);
    

    You can convert your private key into PKCS#8 using openssl pkcs8 -topk8 (remember -outform DER, you may also want to check the cipher suites as not all might be commonly supported by both Java and OpenSSL).

    • From a keystore usage point of view:

    If you don’t want to do much programming for handling the keys, to go between Java and OpenSSL, it’s convenient to use the PKCS#12 format.

    If the keys and certs you have produced with OpenSSL are not already in a p12 container:

    openssl pkcs12 -export -in cert.pem -inkey key.pem -out store.p12
    

    In general, you can make use of the directly, using Java’s «PKCS12» keystore type (instead of «JKS» by default).

    If needed, you can convert this PKCS12 keystore into another format (e.g. JKS) using keytool (Java 6+):

    keytool -importkeystore -srckeystore store.p12 -srcstoretype PKCS12 
         -destkeystore store.jks -deststoretype JKS
    

    (Essentially, the opposite operation as the one described in this question.)

    Either way, whether from using PEMReader or by loading your key/cert from a KeyStore, you should be able to get instances of PrivateKey and Certificate (or PublicKey directly).

    You can verify the signature of a Certificate has been done using by the private key matching a given public key using its verify(PublicKey) method.

    With them, you can also use the digital signature API. It’s a more general API for any document signature, and I wouldn’t necessarily verify a certificate signature with it (I’d rather use the certification path API for this, since it will also build the chain).

    case of «UnrecoverableKeyException: DER input, Integer tag error»?

  • use the [CODE] tags — it makes it much easier for people to help you.

  • after searching the net for hours, it turns out the problem is how the KeyStore is initialized. the java tutorial on the sun site says that the default provider should be fine, but it’s not.

    hope that saves someone some agony.
    Jon

    use the [CODE] tags — it makes it much easier for people to help you.

  • hope that saves someone some agony.
    Jon[/QB]

    GOD BLESS YOU JON.
    I can pass one further tip on for using keystores.
    Don’t try and create one manually the first time. It don’t work!
    I got this from somewhere else on the web — here is my function for creating keystores — it basically invokes the keystore tool and then picks up the output.
    You may have to edit it a little.
    Again, hope it helps someone, like Jon helped me 🙂

    IM
    (I edited the post to fix the typo involved in the code tags — JAM)
    [ August 25, 2003: Message edited by: Joel McNary ]

    Источник

    Unable to generate private key from password-protected private key

    I’ve been writing some code to sign data. So far this is what I have
    The problem is that I’m getting the following exception and I can’t find infomation about it.
    What does DER input, Integer tag error means? How can I read a password-protected PKCS8 DER private key to sign a file?

    Thanks so much in advance .

    Edited by: 879653 on 09-dic-2011 15:44

    Answers

    I was thinking the same. I don’t know how was it generated, the government is giving them so the people can pay their taxes over internet. In the page of the government it says that *»the private key is a file with .key extension as defined in the standard PKCS8 and is ciphered by the same specifications of standard PKCS1″*

    It uses RSA as algorithm, that’s 100% sure.

    I don’t know anything about the envelope so I can’t tell you if it has something like that.

    By the way, it has a password that protects the private key, doesn’t it has something to do with my problem? Just guessing.

    Finally, is there a way to know what format it is? I have the certificate that belongs to that key and I can read it with OpenSSL, I don’t know if that helps though.

    Thanks for answering.

    That scares me! This means that the government have access to your private key so it is not very private. Only you should have access to your private key; not your government, your cousin, your uncle, your lawyer or even your wife.

    It uses RSA as algorithm, that’s 100% sure.

    I don’t know anything about the envelope so I can’t tell you if it has something like that.

    Open the key file with a text editor. If it is a text file then it should have a header saying something like RSA PRIVATE KEY with a Base64 encoded body (the actual private key). If it is not a text file then I can’t help without access to it and it does not make security sense to give me access.

    Does the government also supply the password? If not then presumably they provide some software for you to use that has the password compiled into it.

    Источник

    «algid parse error, not a sequence» on encrypt-config-value with RSA private key #13

    Comments

    cjr8020 commented Jan 14, 2016

    I wanted to encrypt a config value using the RSA algorithm.
    I also wanted to «publish» the public key, and keep the private key private.

    Generating RSA key:

    Following your directions: «for encrypting values. In the case of non-symmetric algorithms (e.g. RSA) specify the private key»..

    Encrypting a value using private key:

    For the sake of experimentation, encrypting a value without referencing the private key explicitly succeeds:

    . and the service can successfully decrypt the encrypted value in the config.yml.

    However, this bundle seems to require that both, public and private, keys are found in var/conf directory.

    The benefit of using an asymmetric algorithm like RSA would be allowing me to publish the public key and keep the private key private. I tried moving the private key from var/conf directory and leaving just the public key there and got this error:

    Am I missing something obvious here?
    Thanks

    The text was updated successfully, but these errors were encountered:

    bavardage commented Jan 14, 2016

    To the first point — I made a mistake in the readme, sorry — will push a fix. The public key is used for encryption (producing the encrypted values), the private key for decryption (reading the encrypted values from the config and decrypting them for the app to use).

    The readme should say «for encrypting values. In the case of non-symmetric algorithms (e.g. RSA) specify the public key»

    For the second point, when running, the current code path assumes you have the public and private keys in var/conf, although only the private key is used.

    An example use of the non-symmetric keys:

    1. Install your service on host1, generate the keypair (public and private)
    2. Transfer the public key to host2
    3. Install something giving you the encrypted-config-value cli on host2
    4. Use the cli to encrypt a config value, specifying the path to the public key
    5. Put that encrypted value into the config on host1 (manually/using some deploy script. )
    6. Run the service on host1, and it will decrypt the value (using the private key)

    The rough intent here is that only the running service on host1 can read the encrypted values, yet we could produce the configuration files in some other place, as long as we have the public key.

    Above you mention «I tried moving the private key from var/conf directory and leaving just the public key there and got this error:». Was this when running your actual dropwizard service or when running a command? From the stacktrace, it looks like the former — in which case, you’ll need to have a private key in order to be able to decrypt the value in the config file.

    I think a potential enhancement here is to allow running the service without a public key present, since it’s kinda superfluous.

    cjr8020 commented Jan 14, 2016

    Hi Ben, thanks for looking into this, and great bundle!

    The last exception occurred when I was launching the actual dw service with java -jar server config.yml as it was attempting to read the config.

    It would be a great enhancement if only one key had to be available to the dw service at startup time. Otherwise, with both, public and private, keys present in one place, there is no real advantage to use RSA over AES.

    Using Alice and Bob as a reference, Alice gives Bob her public key only, and Bob can now create an encrypted message with it. Alice will use her private key to read the encrypted message.

    1. An admin creates an encrypted value by running «encrypt-config-value» (which should ideally only require the public key) on host0 (his admin workstation).
    2. The dw service instance deployed on hostN should only require the private key to be present (in var/conf) in order to be able to decrypt the encrypted config value.

    Semantically, you could also reverse the notions, but that’s in the eye of the beholder..

    Currently this is what happens at dw service startup time when one or the other key is removed from var/conf:

    private only — the code simply expects to find both:

    public key only in var/conf — the public key cannot be used to decrypt the encrypted value:

    Источник

    «algid parse error, not a sequence» on encrypt-config-value with RSA private key #13

    Comments

    cjr8020 commented Jan 14, 2016

    I wanted to encrypt a config value using the RSA algorithm.
    I also wanted to «publish» the public key, and keep the private key private.

    Generating RSA key:

    Following your directions: «for encrypting values. In the case of non-symmetric algorithms (e.g. RSA) specify the private key»..

    Encrypting a value using private key:

    For the sake of experimentation, encrypting a value without referencing the private key explicitly succeeds:

    . and the service can successfully decrypt the encrypted value in the config.yml.

    However, this bundle seems to require that both, public and private, keys are found in var/conf directory.

    The benefit of using an asymmetric algorithm like RSA would be allowing me to publish the public key and keep the private key private. I tried moving the private key from var/conf directory and leaving just the public key there and got this error:

    Am I missing something obvious here?
    Thanks

    The text was updated successfully, but these errors were encountered:

    bavardage commented Jan 14, 2016

    To the first point — I made a mistake in the readme, sorry — will push a fix. The public key is used for encryption (producing the encrypted values), the private key for decryption (reading the encrypted values from the config and decrypting them for the app to use).

    The readme should say «for encrypting values. In the case of non-symmetric algorithms (e.g. RSA) specify the public key»

    For the second point, when running, the current code path assumes you have the public and private keys in var/conf, although only the private key is used.

    An example use of the non-symmetric keys:

    1. Install your service on host1, generate the keypair (public and private)
    2. Transfer the public key to host2
    3. Install something giving you the encrypted-config-value cli on host2
    4. Use the cli to encrypt a config value, specifying the path to the public key
    5. Put that encrypted value into the config on host1 (manually/using some deploy script. )
    6. Run the service on host1, and it will decrypt the value (using the private key)

    The rough intent here is that only the running service on host1 can read the encrypted values, yet we could produce the configuration files in some other place, as long as we have the public key.

    Above you mention «I tried moving the private key from var/conf directory and leaving just the public key there and got this error:». Was this when running your actual dropwizard service or when running a command? From the stacktrace, it looks like the former — in which case, you’ll need to have a private key in order to be able to decrypt the value in the config file.

    I think a potential enhancement here is to allow running the service without a public key present, since it’s kinda superfluous.

    cjr8020 commented Jan 14, 2016

    Hi Ben, thanks for looking into this, and great bundle!

    The last exception occurred when I was launching the actual dw service with java -jar server config.yml as it was attempting to read the config.

    It would be a great enhancement if only one key had to be available to the dw service at startup time. Otherwise, with both, public and private, keys present in one place, there is no real advantage to use RSA over AES.

    Using Alice and Bob as a reference, Alice gives Bob her public key only, and Bob can now create an encrypted message with it. Alice will use her private key to read the encrypted message.

    1. An admin creates an encrypted value by running «encrypt-config-value» (which should ideally only require the public key) on host0 (his admin workstation).
    2. The dw service instance deployed on hostN should only require the private key to be present (in var/conf) in order to be able to decrypt the encrypted config value.

    Semantically, you could also reverse the notions, but that’s in the eye of the beholder..

    Currently this is what happens at dw service startup time when one or the other key is removed from var/conf:

    private only — the code simply expects to find both:

    public key only in var/conf — the public key cannot be used to decrypt the encrypted value:

    Источник

    Шифрование с помощью закрытого ключа RSA в Java

    Я пытаюсь зашифровать некоторый контент с помощью секретного ключа RSA.

    но превращая его в использование закрытых ключей, а не публичных. Следуя этому примеру, я думаю, что мне нужно сделать следующее:

    • Чтение в закрытом ключе формата DER
    • Создать PCKS8EncodedKeySpec
    • вызов generatePrivate() из KeyFactory для получения объекта закрытого ключа
    • Используйте этот объект закрытого ключа с объектом Cipher для шифрования

    Ключ был сгенерирован из openssl:

    openssl genrsa -aes256 -out private.pem 2048

    а затем преобразован в формат DER с помощью:

    openssl rsa -in private.pem -outform DER -out private.der

    Я генерирую PKCS8EncodedKeySpec с помощью:

    И затем сгенерируйте закрытый ключ с помощью:

    Однако при вызове:

    • Правильно ли подходит общий подход?
    • Используется ли PCKS8EncodedKeySpec правильный ключ?
    • Любые мысли о неверной ошибке спецификации ключа?

    5 ответов

    Прежде всего, я смущен, почему вы планируете использовать Cipher для шифрования с помощью закрытого ключа, а не для подписания с Signature . Я не уверен, что все поставщики RSA Cipher будут использовать правильный тип блока для настройки, но стоит попробовать.

    Отметив это, я думаю, что вы пытаетесь загрузить нестандартный ключ OpenSSL. Преобразование его в DER с помощью rsa — это просто декодирование с базой 64; структура ключа не является PKCS # 8.

    Вместо этого после genrsa используйте команду openssl pkcs8 для преобразования сгенерированного ключа в незашифрованный формат PKCS # 8, DER:

    Это приведет к созданию незашифрованного закрытого ключа, который может быть загружен с помощью PKCS8EncodedKeySpec .

    Вы не можете шифровать с помощью закрытого ключа. Если JCE позволяет вам это сделать, это просто случайно.

    Вам нужно использовать подпись. Вот фрагмент кода, чтобы сделать это,

    Не случайно, что шифрование с закрытым ключом разрешено. Если вы хотите разбить подпись на индивидуальное хеширование и шифрование, необходимо шифрование с помощью закрытого ключа. Допустим, у меня есть документ, который мне нужно подписать, а мой ключ находится в сети HSM. Теперь либо я передаю весь документ в HSM, чтобы подписать, либо я могу создать локальный хэш и передать его в HSM только для шифрования. Мой выбор будет зависеть от того, дает ли локальное вычисление хеша лучшую производительность, а именно: делегированное хэш-вычисление с задержкой сети.

    Этот вопрос довольно старый, но я недавно наткнулся на проблему (я выполняю требования к некоторому протоколу, который требует шифрования с закрытым ключом). Я просто напишу сообщение из forum:

    Недавно я наткнулся на ту же проблему, представив PMR 22265,49R и поддержку IBM после консультации с «разработкой» (кто бы это ни был), что частные ключи не могут использоваться для шифрования. Независимо от того, насколько я пытался спорить с ними, что частные ключи не должны использоваться для защиты данных, что является лишь одной из целей шифрования, и что совершенно нормально использовать закрытые ключи для шифрования для достижения отказа от отказа, они были непоколебимы в их вере. Вы должны любить людей, которые настаивают на том, что 2×2 = 5.

    Вот как я работал над этой проблемой: по сути, я создал объект открытого ключа с криптовым материалом с закрытым ключом. Вам нужно будет сделать обратное, создать объект закрытого ключа с криптовальным материалом с открытым ключом, чтобы расшифровать с помощью открытого ключа, если вы хотите, чтобы исключение «Открытый ключ не использовалось для дешифрования».

    Источник

    У меня есть следующий код для чтения закрытого ключа в формате PKCS # 8

    public void encryptHash(String hashToEncrypt, String pathOfKey, String Algorithm) {
        FileInputStream fis = null;
        byte[] encodedKey = null;
        try {
    
            File f = new File(pathOfKey);
            encodedKey = new byte[(int)f.length()];
    
            fis = new FileInputStream(f);
            fis.read(encodedKey);
            fis.close();
    
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
    
            Signature rsaSigner = Signature.getInstance("SHA1withRSA");
            rsaSigner.initSign(privateKey);
    
            fis = new FileInputStream(hashToEncrypt);
            BufferedInputStream bis = new BufferedInputStream(fis);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = bis.read(buffer)) >= 0) {
                try {
                    rsaSigner.update(buffer, 0, len);
                } catch (SignatureException ex) {
                    Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            bis.close();
    
            byte[] signature = rsaSigner.sign();
    
            System.out.println(new String(signature));
    
        } catch (SignatureException ex) {
            Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    

    Но я получаю следующее исключение.

    dic 09, 2011 1:59:59 PM firmaelectronica.DataEncryptor encryptHash
    Grave: null
    java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error
        at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
        at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
        at firmaelectronica.DataEncryptor.encryptHash(DataEncryptor.java:40)
        at firmaelectronica.FirmaElectronica.main(FirmaElectronica.java:39)
    Caused by: java.security.InvalidKeyException: IOException : DER input, Integer tag error
        at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:361)
        at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:367)
        at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
        at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
        at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
        at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
        ... 3 more
    

    есть идеи, что не так? Я пробовал это на OpenSSL openssl pkcs8 -inform DER -in aaa010101aaa_FIEL.key -out aaa010101aaa_FIEL_key.pem и он работает, но когда я хочу прочитать ключ в формате DER, он просто отправляет это исключение.

    Понравилась статья? Поделить с друзьями:
  • Java runtime error что это
  • Java runtime environment not found как исправить
  • Java runtime environment error log
  • Java rmi error unmarshalling arguments
  • Java retry on error