Посмотреть содержимое keystore linux

How to check certificate name and alias in keystore files?

I have a bunch of .keystore files and need to find one with specific CN and alias. Is there a way to do it with keytool, jarsigner or some other tool? I found a way to check if specific keystore was used to sign a specific apk, but I also need to get the alias and certificate name in each of the files.

12 Answers 12

You can run the following command to list the content of your keystore file (and alias name):

keytool -v -list -keystore /path/to/keystore 

If you are looking for a specific alias (for example foo), you can also specify it in the command:

keytool -list -keystore /path/to/keystore -alias foo 

If the alias is not found, it will display an exception:

keytool error: java.lang.Exception: Alias does not exist

Hi can I display the key alias password If I know the key alias name and have keystore certificate and keystore password

@prateek You can’t. There wouldn’t be much point in having keystore or key passwords if you could just display then with a command-line tool.

You can run the following command to list the content of your keystore file: keytool -list -keystore .keystore The above commond is not providing the name of alias

I think that /path/to/keystore instead of .keystore would be more clear to the reader. Anyway it is the correct answer!

In order to get all the details I had to add the -v option to romaintaz answer:

keytool -v -list -keystore .keystore 

«If the -v option is specified, then the certificate is printed in human-readable format, with additional information such as the owner, issuer, serial number, and any extensions.» (see: Java SE Tools Reference, Display Data command, -list option)

You can run from Java code.

try < File file = new File(keystore location); InputStream is = new FileInputStream(file); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); String password = "password"; keystore.load(is, password.toCharArray()); Enumerationenumeration = keystore.aliases(); while(enumeration.hasMoreElements()) < String alias = enumeration.nextElement(); System.out.println("alias name: " + alias); Certificate certificate = keystore.getCertificate(alias); System.out.println(certificate.toString()); >> catch (java.security.cert.CertificateException e) < e.printStackTrace(); >catch (NoSuchAlgorithmException e) < e.printStackTrace(); >catch (FileNotFoundException e) < e.printStackTrace(); >catch (KeyStoreException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >finally < if(null != is) try < is.close(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> 

Certificate class holds all information about the keystore.

Читайте также:  Linux booting from usb

UPDATE- OBTAIN PRIVATE KEY

Key key = keyStore.getKey(alias, password.toCharArray()); String encodedKey = new Base64Encoder().encode(key.getEncoded()); System.out.println("key ? " + encodedKey); 

@prateek Hope this is what you looking for!

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.cert.Certificate; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.Enumeration;

@Renjith hello This code displays everything except the password associated with alias, How can I display it . Please help me

@Renjith java.security.UnrecoverableKeyException this is the exception thrown when I try this code actualy I want to retrieve alias password

I didnt have Base64Encoder class. Can you please tell me which jar file does it have? or is it a .java file?

KeyStore Explorer open source visual tool to manage keystores.

This is close to a link-only answer. The policy is that you should post some information on how to use the tool/library in the answer itself.

In a bash-like environment you can use:

keytool -list -v -keystore cacerts.jks | grep 'Alias name:' | grep -i foo 

This command consist of 3 parts. As stated above, the 1st part will list all trusted certificates with all the details and that’s why the 2nd part comes to filter only the alias information among those details. And finally in the 3rd part you can search for a specific alias (or part of it). The -i turns the case insensitive mode on. Thus the given command will yield all aliases containing the pattern ‘foo’, f.e. foo, 123_FOO, fooBar, etc. For more information man grep .

Источник

Команды Java Keytool

Java Keytool — это утилита для управления ключами и сертификатами. Она позволяет пользователям управлять своими собственными парами открытых/закрытых ключей и сертификатами . Она также позволяет пользователям кэшировать сертификаты. Java Keytool хранит ключи и сертификаты в так называемом хранилище ключей. По умолчанию хранилище ключей Java реализовано в виде файла. Он защищает закрытые ключи паролем. Хранилище ключей Keytool содержит закрытый ключ и любые сертификаты, необходимые для завершения цепочки доверия и установления надежности основного сертификата.

Каждый сертификат в хранилище ключей Java связан с уникальным псевдонимом. При создании хранилища ключей Java вы сначала создадите файл .jks, который изначально будет содержать только закрытый ключ. Затем вы сгенерируете CSR, и на его основе будет сгенерирован сертификат. Затем вы импортируете сертификат в хранилище ключей, включая все корневые сертификаты. Java Keytool также имеет несколько других функций, которые позволяют просматривать сведения о сертификате или перечислять сертификаты, содержащиеся в хранилище ключей, или экспортировать сертификаты.

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

Читайте также:  Linux install kernel devel

Команды Java Keytool для создания и импорта

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

Создайте хранилище ключей Java и пару ключей

keytool -genkey -alias kuzevanov.ru -keyalg RSA -keystore /etc/pki/java/cacerts -keysize 2048

Создайте запрос на подпись сертификата (CSR) для существующего хранилища ключей Java

keytool -certreq -alias kuzevanov.ru -keystore /etc/pki/java/cacerts -file file_cert.csr

Импорт корневого или промежуточного сертификата ЦС в существующее хранилище ключей Java

keytool -import -trustcacerts -alias root -file name_cert.crt -keystore /etc/pki/java/cacerts

Импорт подписанного первичного сертификата в существующее хранилище ключей Java

keytool -import -trustcacerts -alias kuzevanov.ru -file name_sert.crt -keystore /etc/pki/java/cacerts

Создайте хранилище ключей и самозаверяющий сертификат

keytool -genkey -keyalg RSA -alias selfsigned -keystore /etc/pki/java/cacerts -storepass password -validity 360 -keysize 2048

Команды Java Keytool для проверки

Если вам нужно проверить информацию в сертификате или хранилище ключей Java, используйте эти команды.

Проверить автономный сертификат

keytool -printcert -v -file name_sert.crt

Проверьте, какие сертификаты находятся в хранилище ключей Java

keytool -list -v -keystore /etc/pki/java/cacerts

Проверьте конкретную запись хранилища ключей, используя псевдоним

keytool -list -v -keystore /etc/pki/java/cacerts -alias kuzevanov.ru

Другие команды Java Keytool

Удалить сертификат из хранилища ключей Java Keytool

keytool -delete -alias kuzevanov.ru -keystore /etc/pki/java/cacerts

Изменить пароль хранилища ключей Java

keytool -storepasswd -new new_storepass -keystore /etc/pki/java/cacerts

Экспорт сертификата из хранилища ключей

keytool -export -alias kuzevanov.ru -file name_sert.crt -keystore /etc/pki/java/cacerts

Получение списка доверенных сертификатов ЦС

keytool -list -v -keystore $JAVA_HOME/jre/lib/security/cacerts

Импорт нового ЦС в доверенные сертификаты

keytool -import -trustcacerts -file /path/to/ca/ca.pem -alias CA_ALIAS -keystore $JAVA_HOME/jre/lib/security/cacerts

Источник

How to list the certificates stored in a PKCS12 keystore with keytool?

If the keystore is PKCS12 type ( .pfx ) you have to specify it with -storetype PKCS12 (line breaks added for readability):

keytool -list -v -keystore \ -storepass \ -storetype PKCS12 

If you prefer a graphical interface utility I found Keystore Explorer, a open source GUI replacement for the Java command-line utilities keytool, jarsigner and jadtool. keystore-explorer.sourceforge.net

Thanks for the tip @David. Nice to see the project is still active also, unlike so many other such projects!

You can also use openssl to accomplish the same thing:

$ openssl pkcs12 -nokeys -info \ -in \ -passin pass: MAC Iteration 2048 MAC verified OK PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048 Certificate bag Bag Attributes localKeyID: XX XX XX XX XX XX XX XX XX XX XX XX XX 48 54 A0 47 88 1D 90 friendlyName: jedis-server subject=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXX/CN=something1 issuer=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXXX/CN=something1 -----BEGIN CERTIFICATE----- . . . -----END CERTIFICATE----- PKCS7 Data Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048 

I wanted to see the alias aka friendlyname. Had to use «openssl pkcs12 -nodes -in -passin pass:«

Читайте также:  Hp laserjet p2035 драйвер линукс

If you get a decryption error, you might need to specify -nodes and -legacy . See also stackoverflow.com/questions/72598983/…

You can list down the entries (certificates details) with the keytool and even you don’t need to mention the store type. Also, the .p12 and .pfx are both PKCS#12 files. Assume that you’ve the keystore file cert.pfx or cert.p12 then you can use the following command to list down the content.

keytool -list -v -keystore cert.pfx -storepass
keytool -list -v -keystore cert.p12 -storepass Keystore type: PKCS12 Keystore provider: SunJSSE Your keystore contains 1 entry Alias name: 1 Creation date: Jul 11, 2020 Entry type: PrivateKeyEntry Certificate chain length: 2 

Pls consider of explaining your code and how it would help, so that others can be benefited from this.

openssl pkcs12 -info -in keystore_file 

What is missing in the question and all the answers is that you might need the passphrase to read public data from the PKCS#12 (.pfx) keystore. If you need a passphrase or not depends on how the PKCS#12 file was created. You can check the ASN1 structure of the file (by running it through a ASN1 parser, openssl or certutil can do this too), if the PKCS#7 data (e.g. OID prefix 1.2.840.113549.1.7) is listed as ‘encrypted’ or with a cipher-spec or if the location of the data in the asn1 tree is below an encrypted node, you won’t be able to read it without knowledge of the passphrase. It means your ‘openssl pkcs12’ command will fail with errors (output depends on the version). For those wondering why you might be interested in the certificate of a PKCS#12 without knowledge of the passphrase. Imagine you have many keystores and many phassphrases and you are really bad at keeping them organized and you don’t want to test all combinations, the certificate inside the file could help you find out which password it might be. Or you are developing software to migrate/renew a keystore and you need to decide in advance which procedure to initiate based on the contained certicate without user interaction. So the latter examples work without passphrase depending on the PKCS#12 structure.

Just wanted to add that, because I didn’t find an answer myself and spend a lot of time to figure it out.

Источник

Оцените статью
Adblock
detector