Hello,
Through several articles, I would like present the cryptographic mechanisms, types of keys, certificate, types of algorithms …etc:
- PRESENTATION : Concepts of Cryptography (concepts, types of keys symmetric/asymmetric, …)
- The principles of SSL
- The principles of Signature and Certificate
- The principles of Hardware Security Module HSM
- Encoding with base64, base64url, rfc-4648
- Encryption with Blowfish (Anonymization)
- Encryption with AES/CBC, AES/EBC (Encryption of files)
- Encryption with PBEWithMD5AndDES (Encryption of files)
- Encryption with RSA (asymmetric keys private and public)
- KeyStore, JCEKS, SecretKey, PrivateKey, PublicKey, Certificate
- Example, Use of SecretKey, PrivateKey, PublicKey, CSV file (CryptoTools, GenericObfuscationFile)
KeyStore, JCEKS, SecretKey, PrivateKey, PublicKey, Certificate
- Presentation
The Java™ Cryptography Architecture Standard Algorithm Name Documentation describes several KeyStore Types to used during the generation of a KeyStore’s instance (see https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html):
- jceks = The proprietary keystore implementation provided by the SunJCE provider.
- jks = The proprietary keystore implementation provided by the SUN provider.
- pkcs12 = The transfer syntax for personal identity information as defined in PKCS #12.
As described in the KeyStore JavaDoc https://docs.oracle.com/javase/7/docs/api/java/security/KeyStore.html KeyStore manages different types of entries. Each type of entry implements the KeyStore.Entry interface. Three basic KeyStore.Entry implementations are provided:
- KeyStore.PrivateKeyEntry : This type of entry holds a cryptographic PrivateKey, which is optionally stored in a protected format to prevent unauthorized access. It is also accompanied by a certificate chain for the corresponding public key. Private keys and certificate chains are used by a given entity for self-authentication. Applications for this authentication include software distribution organizations which sign JAR files as part of releasing and/or licensing software.
- KeyStore.SecretKeyEntry : This type of entry holds a cryptographic SecretKey, which is optionally stored in a protected format to prevent unauthorized access.
- KeyStore.TrustedCertificateEntry : This type of entry contains a single public key Certificate belonging to another party. It is called a trusted certificate because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the subject (owner) of the certificate. This type of entry can be used to authenticate other parties.
- Tools: KeyStoreManagement Class
In my previous posts, I exposed the use of PorteCle tool used in order to generate KeyStore/TrustStore, self-signed certificate,…etc:- http://www.javablog.fr/java-ssl-generate-keystore-self-signed-certificate-tool-portecle.html
- http://www.javablog.fr/java-ssl-generate-truststore-self-signed-certificate-tool-zportecle.html
…. in this post, I would expose you my homemade utility class KeyStoreManagement composed of following methods in order to generate KeyStore/TrustStore, add/get/check secret key, private key, public key and certificate,…etc:
- KeyStore createOrUseKeyStore(…) : creation or use of JCEKS Keystore managed by a password;
01
private
static
KeyStore createOrUseKeyStore(String ksFileName, String ksPassword)
throws
Exception {
02
// KeyStore Types
03
final
KeyStore ks = KeyStore.getInstance(
"JCEKS"
);
// or KeyStore.getDefaultType()
04
05
InputStream input =
null
;
06
File f =
new
File(ksFileName);
07
if
(f.exists()) {
08
input =
new
FileInputStream(f);
09
// .keystore file already exists => load it
10
ks.load(input, ksPassword.toCharArray());
11
12
}
else
{
13
// .keystore file not created yet => create it
14
ks.load(
null
,
null
);
15
ks.store(
new
FileOutputStream(ksFileName), ksPassword.toCharArray());
16
}
17
18
return
ks;
19
}
- void addSecretKey(…) : method adding a password-protected secret key to the keystore. The SecretKeyEntry entry is password-protected.
1
public
void
addSecretKey(String keyEntryName, String keyEntryPassword, SecretKey secretKey)
throws
Exception {
2
KeyStore.SecretKeyEntry keyStoreEntry =
new
KeyStore.SecretKeyEntry(secretKey);
3
KeyStore.PasswordProtection keyPassword =
new
KeyStore.PasswordProtection(keyEntryPassword.toCharArray());
4
keyStore.setEntry(keyEntryName, keyStoreEntry, keyPassword);
5
keyStore.store(
new
FileOutputStream(keyStoreFileName), keyStorePassword.toCharArray());
6
}
- void addCertificate(…) : method adding a NOT-protected certificate to the keystore. TheTrustedCertificateEntry is NOT protected. A Certificate contains the a public key.
1
public
void
addCertificate(String keyEntryName, Certificate trustedCert)
throws
Exception {
2
KeyStore.TrustedCertificateEntry keyStoreEntry =
new
KeyStore.TrustedCertificateEntry(trustedCert);
3
keyStore.setEntry(keyEntryName, keyStoreEntry,
null
);
4
keyStore.store(
new
FileOutputStream(keyStoreFileName), keyStorePassword.toCharArray());
5
}
- void addPrivateKey(…) : method adding a password-protected private key to the keystore. The PrivateKeyEntry entry is password-protected.
1
public
void
addPrivateKey(String keyEntryName, String keyEntryPassword, PrivateKey privateKey, Certificate[] certificatesChain)
throws
Exception {
2
KeyStore.PrivateKeyEntry keyStoreEntry =
new
KeyStore.PrivateKeyEntry(privateKey, certificatesChain);
3
KeyStore.PasswordProtection keyPassword =
new
KeyStore.PasswordProtection(keyEntryPassword.toCharArray());
4
keyStore.setEntry(keyEntryName, keyStoreEntry, keyPassword);
5
keyStore.store(
new
FileOutputStream(keyStoreFileName), keyStorePassword.toCharArray());
6
}
- SecretKey getSecretKey(…) : method allowing the getting a secret key from keystore. The entry and keystore are protected by different passwords.
01
public
SecretKey getSecretKey(String keyEntryName, String keyEntryPassword)
throws
Exception {
02
if
(StringUtils.isEmpty(keyEntryName)) {
03
throw
new
IllegalArgumentException(
"Key entry name should be provided"
);
04
}
05
KeyStore.PasswordProtection keyPassword =
new
KeyStore.PasswordProtection(keyEntryPassword.toCharArray());
06
KeyStore.Entry entry = keyStore.getEntry(keyEntryName, keyPassword);
07
if
(entry==
null
){
08
return
null
;
09
}
else
{
10
SecretKey keyFound = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
11
return
keyFound;
12
}
13
}
- PrivateKey getPrivateKey(…) : method allowing the getting a private key from keystore. The entry and keystore are protected by different passwords.
01
public
PrivateKey getPrivateKey(String keyEntryName,
final
String keyEntryPassword)
throws
Exception {
02
if
(StringUtils.isEmpty(keyEntryName)) {
03
throw
new
IllegalArgumentException(
"Key entry name should be provided"
);
04
}
05
KeyStore.PasswordProtection keyPassword =
new
KeyStore.PasswordProtection(keyEntryPassword.toCharArray());
06
KeyStore.Entry entry = keyStore.getEntry(keyEntryName, keyPassword);
07
if
(entry==
null
){
08
return
null
;
09
}
else
{
10
PrivateKey keyFound = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey();
11
return
keyFound;
12
}
13
}
- Certificate getCertificate(…) : method allowing the getting a certificate from keystore. The entry TrustedCertificateEntry is NOT protected but the keystore is protected by password.
01
public
Certificate getCertificate(String keyEntryName)
throws
Exception {
02
if
(StringUtils.isEmpty(keyEntryName)) {
03
throw
new
IllegalArgumentException(
"Key entry name should be provided"
);
04
}
05
KeyStore.Entry entry = keyStore.getEntry(keyEntryName,
null
);
06
if
(entry==
null
){
07
return
null
;
08
}
else
{
09
Certificate certificatFound = ((KeyStore.TrustedCertificateEntry) entry).getTrustedCertificate();
10
if
(certificatFound ==
null
) {
11
throw
new
IllegalArgumentException(String.format(
"No certificate found for alias '%s'"
, keyEntryName));
12
}
13
return
certificatFound;
14
}
15
}
- PublicKey getPublicKeyOfCertificate(…) : method allowing the getting a public key contained in certificate from keystore. The entry TrustedCertificateEntry is NOT protected but the keystore is protected by password.
01
public
PublicKey getPublicKeyOfCertificate(String keyEntryName)
throws
Exception {
02
if
(StringUtils.isEmpty(keyEntryName)) {
03
throw
new
IllegalArgumentException(
"Key entry name should be provided"
);
04
}
05
KeyStore.Entry entry = keyStore.getEntry(keyEntryName,
null
);
06
if
(entry==
null
){
07
return
null
;
08
}
else
{
09
Certificate certificatFound = ((KeyStore.TrustedCertificateEntry) entry).getTrustedCertificate();
10
if
(certificatFound ==
null
) {
11
throw
new
IllegalArgumentException(String.format(
"No certificate found for alias '%s'"
, keyEntryName));
12
}
13
return
certificatFound.getPublicKey();
14
}
15
}
- boolean hasSecretKey(…) : method checking if a secret key is stored in keystore. The entry and keystore are protected by different passwords.
1
public
boolean
hasSecretKey(String keyEntryName, String keyEntryPassword,
byte
[] keyValue)
throws
Exception {
2
KeyStoreManagement keyStoreManagement =
new
KeyStoreManagement(
this
.keyStoreFileName,
this
.keyStorePassword);
3
SecretKey tmp = keyStoreManagement.getSecretKey(keyEntryName, keyEntryPassword);
4
if
(tmp ==
null
){
5
return
false
;
6
}
else
{
7
return
new
String(keyValue).equals(
new
String(tmp.getEncoded()));
8
}
9
}
- boolean hasPrivateKey(…) : method checking if private key is stored in keystore. The entry and keystore are protected by different passwords.
1
public
boolean
hasPrivateKey(String keyEntryName, String keyEntryPassword,
byte
[] keyValue)
throws
Exception {
2
KeyStoreManagement keyStoreManagement =
new
KeyStoreManagement(
this
.keyStoreFileName,
this
.keyStorePassword);
3
PrivateKey tmp = keyStoreManagement.getPrivateKey(keyEntryName, keyEntryPassword);
4
if
(tmp ==
null
){
5
return
false
;
6
}
else
{
7
return
new
String(keyValue).equals(
new
String(tmp.getEncoded()));
8
}
9
}
- boolean hasCertificate(…) : method checking if certificate is stored in keystore. ONLY the keystore is protected by password.
1
public
boolean
hasCertificate(String keyEntryName,
byte
[] certificateValue)
throws
Exception {
2
KeyStoreManagement keyStoreManagement =
new
KeyStoreManagement(
this
.keyStoreFileName,
this
.keyStorePassword);
3
Certificate tmp = keyStoreManagement.getCertificate(keyEntryName);
4
if
(tmp ==
null
){
5
return
false
;
6
}
else
{
7
return
new
String(certificateValue).equals(
new
String(tmp.getEncoded()));
8
}
9
}
- boolean hasPublicKeyOfCertificate(…) : method checking if public key containd in a certificate is stored in keystore. ONLY the keystore is protected by password.
01
public
boolean
hasPublicKeyOfCertificate(String keyEntryName,
byte
[] keyValue)
throws
Exception {
02
KeyStoreManagement keyStoreManagement =
new
KeyStoreManagement(
this
.keyStoreFileName,
this
.keyStorePassword);
03
Certificate tmp = keyStoreManagement.getCertificate(keyEntryName);
04
if
(tmp ==
null
|| tmp.getPublicKey()==
null
){
05
return
false
;
06
}
else
{
07
PublicKey keyTmp = tmp.getPublicKey();
08
return
new
String(keyValue).equals(
new
String(keyTmp.getEncoded()));
09
}
10
}
- Example : Class Test of JCEKS Keystore Management
…The information concerning the keystore (filename, password-protection) and the contained keys (name, password-protected) are stored in a properties file ConfigKeystore.properties
keystore_name=myHuoKeystore.keystore
keystore_pwd=123java.LU321
#
keystore_secretkey1_entry_name=KeyStoReP@sswd4SecrEtKEy1eNtry
keystore_secretkey1_entry_pwd=KeYp@sswdStoreSecrEtEntry1Pwd
keystore_secretkey2_entry_name=KeyStoReP@sswd4SecrEtKEy2eNtry
keystore_secretkey2_entry_pwd=KeYp@sswdStoreSecrEtEntry2Pwd
#
keystore_privatekey_entry_name=KeyStoReP@sswd4PrivAteKEyeNtry
keystore_privatekey_entry_pwd=KeYp@sswdStorePrivATeEntryPwd
#
keystore_certificate_entry_name=KeyStoReP@sswd4CertiFicaTeeNtry1
public
static
Properties getProperties()
throws
Exception {
2
Properties prop =
new
Properties();
3
String filename = System.getProperty(
"user.dir"
) +
"/resources/ConfigKeystore.properties"
;
4
prop.load(
new
FileReader(
new
File(filename).getPath()));
5
return
prop;
6
}
…In the JDK1.7.0_79, the class sun.security.x509.X500Signer has been removed, so, for our tests, we will create this simple package with corresponding package:01
package
sun.security.x509;
02
03
import
java.security.Signature;
04
import
java.security.SignatureException;
05
import
java.security.Signer;
06
import
java.security.NoSuchAlgorithmException;
07
08
/**
09
* This class provides a binding between a Signature object and an
10
* authenticated X.500 name (from an X.509 certificate chain), which
11
* is needed in many public key signing applications.
12
*/
13
public
final
class
X500Signer
extends
Signer
14
{
15
private
static
final
long
serialVersionUID = -8609982645394364834L;
16
17
/**
18
* Called for each chunk of the data being signed. That
19
* is, you can present the data in many chunks, so that
20
* it doesn't need to be in a single sequential buffer.
21
*
22
* @param buf buffer holding the next chunk of the data to be signed
23
* @param offset starting point of to-be-signed data
24
* @param len how many bytes of data are to be signed
25
* @exception SignatureException on errors.
26
*/
27
public
void
update(
byte
buf[],
int
offset,
int
len)
28
throws
SignatureException {
29
sig.update (buf, offset, len);
30
}
31
32
/**
33
* Produces the signature for the data processed by update().
34
*
35
* @exception SignatureException on errors.
36
*/
37
public
byte
[] sign()
throws
SignatureException {
38
return
sig.sign();
39
}
40
41
/**
42
* Returns the algorithm used to sign.
43
*/
44
public
AlgorithmId getAlgorithmId() {
45
return
algid;
46
}
47
48
/**
49
* Returns the name of the signing agent.
50
*/
51
public
X500Name getSigner() {
52
return
agent;
53
}
54
55
/*
56
* Constructs a binding between a signature and an X500 name
57
* from an X.509 certificate.
58
*/
59
// package private ----hmmmmm ?????
60
public
X500Signer(Signature sig, X500Name agent) {
61
if
(sig ==
null
|| agent ==
null
)
62
throw
new
IllegalArgumentException (
"null parameter"
);
63
64
this
.sig = sig;
65
this
.agent = agent;
66
67
try
{
68
this
.algid = AlgorithmId.getAlgorithmId(sig.getAlgorithm());
69
70
}
catch
(NoSuchAlgorithmException e) {
71
throw
new
RuntimeException(
"internal error! "
+ e.getMessage());
72
}
73
}
74
75
private
Signature sig;
76
private
X500Name agent;
// XXX should be X509CertChain
77
private
AlgorithmId algid;
78
}
This class is used during the generation of a self-signed certificate X509:01
public
static
X509Certificate getSelfCertificate (X500Name myname, Date firstDate,
long
validity, String sigAlg, PrivateKey privateKey, PublicKey publicKey)
throws
Exception{
02
X509CertImpl cert;
03
//This class X500Signer has been created in our project in order to compensate the lack of used JDK/JRE.
04
X500Signer issuer =
null
;
05
{
06
Signature signature = Signature.getInstance(sigAlg);
07
signature.initSign (privateKey);
08
issuer =
new
X500Signer (signature, myname);
09
}
10
11
Date lastDate =
new
Date ();
12
lastDate.setTime (firstDate.getTime () + validity *
1000
);
13
14
CertificateValidity interval =
new
CertificateValidity(firstDate,lastDate);
15
16
X509CertInfo info =
new
X509CertInfo();
17
// Add all mandatory attributes
18
info.set(X509CertInfo.VERSION,
new
CertificateVersion(CertificateVersion.V3));
19
info.set(X509CertInfo.SERIAL_NUMBER,
new
CertificateSerialNumber((
int
)(firstDate.getTime()/
1000
)));
20
AlgorithmId algID = issuer.getAlgorithmId();
21
info.set(X509CertInfo.ALGORITHM_ID,
new
CertificateAlgorithmId(algID));
22
info.set(X509CertInfo.SUBJECT,
new
CertificateSubjectName(myname));
23
info.set(X509CertInfo.KEY,
new
CertificateX509Key(publicKey));
24
info.set(X509CertInfo.VALIDITY, interval);
25
info.set(X509CertInfo.ISSUER,
new
CertificateIssuerName(issuer.getSigner()));
26
27
if
(System.getProperty(
"sun.security.internal.keytool.skid"
) !=
null
) {
28
CertificateExtensions ext =
new
CertificateExtensions();
29
ext.set(SubjectKeyIdentifierExtension.NAME,
new
SubjectKeyIdentifierExtension(
new
KeyIdentifier(publicKey).getIdentifier()));
30
info.set(X509CertInfo.EXTENSIONS, ext);
31
}
32
33
cert =
new
X509CertImpl(info);
34
cert.sign(privateKey, sigAlg);
35
return
(X509Certificate)cert;
36
}
…First we need a keystore:1
// Generate the KeyStore
2
KeyStoreManagement keyStoreManagement =
new
KeyStoreManagement(System.getProperty(
"user.dir"
) +
"/resources/"
+ prop.getProperty(
"keystore_name"
), prop.getProperty(
"keystore_pwd"
));
…TEST 1 : SECRET KEY 1 : PBE-MD5-DES01
System.out.println(
"########################## SECRET KEY 1 : PBE-MD5-DES"
);
02
// Generate a SecretKey
03
SecretKey secretKey =
null
;
04
{
05
String encryptionType=
"PBEWithMD5AndDES"
;
06
KeySpec keySpec=
new
PBEKeySpec(
"HUO12JavDotLuX12"
.toCharArray());
07
secretKey = SecretKeyFactory.getInstance(encryptionType).generateSecret(keySpec);
08
}
09
10
11
// Add SecretKey to KeyStore
12
System.out.println(
"#### Add SecretKey to KeyStore : entry="
+prop.getProperty(
"keystore_secretkey1_entry_name"
)+
" and password="
+prop.getProperty(
"keystore_secretkey1_entry_pwd"
));
13
keyStoreManagement.addSecretKey(prop.getProperty(
"keystore_secretkey1_entry_name"
), prop.getProperty(
"keystore_secretkey1_entry_pwd"
), secretKey);
14
15
16
// Check the presence of SecretKey in KeyStore
17
System.out.println(
"#### Check the presence of SecretKey in KeyStore : entry="
+prop.getProperty(
"keystore_secretkey1_entry_name"
)+
" and password="
+prop.getProperty(
"keystore_secretkey1_entry_pwd"
));
18
boolean
isFound = keyStoreManagement.hasSecretKey(prop.getProperty(
"keystore_secretkey1_entry_name"
), prop.getProperty(
"keystore_secretkey1_entry_pwd"
), secretKey.getEncoded());
19
System.out.println(
"=>"
+isFound);
20
21
22
// Get SecretKey from KeyStore
23
System.out.println(
"#### Get SecretKey from KeyStore : entry="
+prop.getProperty(
"keystore_secretkey1_entry_name"
)+
" and password="
+prop.getProperty(
"keystore_secretkey1_entry_pwd"
));
24
SecretKey secretKeyExtract = keyStoreManagement.getSecretKey(prop.getProperty(
"keystore_secretkey1_entry_name"
), prop.getProperty(
"keystore_secretkey1_entry_pwd"
));
25
System.out.println(
"#### Check the value of original SecretKey and the extracted SecretKey : "
);
26
System.out.println(
"=>"
+
new
String(secretKeyExtract.getEncoded()).equals(
new
String(secretKey.getEncoded())));
The outputs should be:
########################## SECRET KEY 1 : PBE-MD5-DES
#### Add SecretKey to KeyStore : entry=KeyStoReP@sswd4SecrEtKEy1eNtry and password=KeYp@sswdStoreSecrEtEntry1Pwd
#### Check the presence of SecretKey in KeyStore : entry=KeyStoReP@sswd4SecrEtKEy1eNtry and password=KeYp@sswdStoreSecrEtEntry1Pwd
=>true
#### Get SecretKey from KeyStore : entry=KeyStoReP@sswd4SecrEtKEy1eNtry and password=KeYp@sswdStoreSecrEtEntry1Pwd
#### Check the value of original SecretKey and the extracted SecretKey :
=>true
…TEST 2 : SECRET KEY 2 : AES 128 bytes01
System.out.println(
"########################## SECRET KEY 2 : AES 128 bytes"
);
02
// Generate a SecretKey
03
SecretKey secretKey =
null
;
04
{
05
KeyGenerator keyGenAes = KeyGenerator.getInstance(
"AES"
);
06
keyGenAes.init(
128
);
07
secretKey = keyGenAes.generateKey();
08
}
09
10
11
// Add SecretKey to KeyStore
12
System.out.println(
"#### Add SecretKey to KeyStore : entry="
+prop.getProperty(
"keystore_secretkey2_entry_name"
)+
" and password="
+prop.getProperty(
"keystore_secretkey2_entry_pwd"
));
13
keyStoreManagement.addSecretKey(prop.getProperty(
"keystore_secretkey2_entry_name"
), prop.getProperty(
"keystore_secretkey2_entry_pwd"
), secretKey);
14
15
16
// Check the presence of SecretKey in KeyStore
17
System.out.println(
"#### Check the presence of SecretKey in KeyStore : entry="
+prop.getProperty(
"keystore_secretkey2_entry_name"
)+
" and password="
+prop.getProperty(
"keystore_secretkey2_entry_pwd"
));
18
boolean
isFound = keyStoreManagement.hasSecretKey(prop.getProperty(
"keystore_secretkey2_entry_name"
), prop.getProperty(
"keystore_secretkey2_entry_pwd"
), secretKey.getEncoded());
19
System.out.println(
"=>"
+isFound);
20
21
22
// Get SecretKey from KeyStore
23
System.out.println(
"#### Get SecretKey from KeyStore : entry="
+prop.getProperty(
"keystore_secretkey2_entry_name"
)+
" and password="
+prop.getProperty(
"keystore_secretkey2_entry_pwd"
));
24
SecretKey secretKeyExtract = keyStoreManagement.getSecretKey(prop.getProperty(
"keystore_secretkey2_entry_name"
), prop.getProperty(
"keystore_secretkey2_entry_pwd"
));
25
System.out.println(
"#### Check the value of original SecretKey and the extracted SecretKey : "
);
26
System.out.println(
"=>"
+
new
String(secretKeyExtract.getEncoded()).equals(
new
String(secretKey.getEncoded())));
The outputs should be:
########################## SECRET KEY 2 : AES 128 bytes
#### Add SecretKey to KeyStore : entry=KeyStoReP@sswd4SecrEtKEy2eNtry and password=KeYp@sswdStoreSecrEtEntry2Pwd
#### Check the presence of SecretKey in KeyStore : entry=KeyStoReP@sswd4SecrEtKEy2eNtry and password=KeYp@sswdStoreSecrEtEntry2Pwd
=>true
#### Get SecretKey from KeyStore : entry=KeyStoReP@sswd4SecrEtKEy2eNtry and password=KeYp@sswdStoreSecrEtEntry2Pwd
#### Check the value of original SecretKey and the extracted SecretKey :
=>true
…TEST 3 : PRIVATE and PUBLIC KEY – RSA 102401
System.out.println(
"########################## PRIVATE and PUBLIC KEY - RSA 1024"
);
02
// Generate a PrivateKey and PublicKey
03
PrivateKey privateKey =
null
;
04
PublicKey publicKey =
null
;
05
X509Certificate certificate =
null
;
06
PublicKey publicKeyInCertificate =
null
;
07
{
08
// METHOD 1 : Use of JAVA classes
09
System.out.println(
"#### Generation of PrivateKey and PublicKey RSA 1024 via the use of JAVA classes"
);
10
KeyPairGenerator keyGenRsa = KeyPairGenerator.getInstance(
"RSA"
);
11
String signatureAlgorithm =
"SHA1WithRSA"
;
12
keyGenRsa.initialize(
1024
);
13
KeyPair keyPair = keyGenRsa.genKeyPair();
14
publicKey = keyPair.getPublic();
15
privateKey = keyPair.getPrivate();
16
//Generate self signed certificate
17
System.out.println(
"#### Generation of self signed certificate with previous PrivateKey and PublicKey RSA 1024"
);
18
certificate = getSelfCertificate(
new
X500Name(
"CN=ROOT"
),
new
Date(), (
long
)
365
*
24
*
3600
, signatureAlgorithm, privateKey, publicKey);
19
publicKeyInCertificate = certificate.getPublicKey();
20
21
// METHOD 2 : Use of CertAndKeyGen class allowing the creation of self-signed X.509 certificates as well as PKCS 10 based certificate signing requests.
22
// Creates a CertAndKeyGen object for a particular key type, signature algorithm, and provider.
23
// o param keyType type of key, e.g. "RSA", "DSA"
24
// o param sigAlg name of the signature algorithm, e.g. "MD5WithRSA", "MD2WithRSA", "SHAwithDSA".
25
// o param providerName name of the provider
26
/*CertAndKeyGen keyGen=new CertAndKeyGen("RSA","SHA1WithRSA",null);
27
keyGen.generate(1024);
28
//Generate self signed certificate
29
publicKey = keyGen.getPublicKey();
30
privateKey = keyGen.getPrivateKey();
31
certificate = keyGen.getSelfCertificate(new X500Name("CN=ROOT"), (long)365*24*3600);
32
publicKeyInCertificate = certificate.getPublicKey();
33
System.out.println(new String(publicKey.getEncoded()).equals(new String(publicKeyInCertificate.getEncoded())));*/
34
}
35
System.out.println(
"#### Check the value of original PublicKey and the PublicKey insided the Certificate: "
);
36
System.out.println(
"=>"
+
new
String(publicKey.getEncoded()).equals(
new
String(publicKeyInCertificate.getEncoded())));
37
38
39
System.out.println(
"#### Creation of Certificate Chain with the previous Certificate"
);
40
X509Certificate[] certificatesChain =
new
X509Certificate[
1
];
41
certificatesChain[
0
]= certificate;
42
43
44
// Add PrivateKey to KeyStore
45
System.out.println(
"#### Add PrivateKey to KeyStore : entry="
+prop.getProperty(
"keystore_privatekey_entry_name"
)+
" and password="
+prop.getProperty(
"keystore_privatekey_entry_pwd"
));
46
keyStoreManagement.addPrivateKey(prop.getProperty(
"keystore_privatekey_entry_name"
), prop.getProperty(
"keystore_privatekey_entry_pwd"
), privateKey, certificatesChain);
47
48
49
// Add Certificate to KeyStore
50
// java.security.KeyStoreException: trusted certificate entries are not password-protected
51
System.out.println(
"#### Add Certificate to KeyStore : entry="
+prop.getProperty(
"keystore_certificate_entry_name"
));
52
keyStoreManagement.addCertificate(prop.getProperty(
"keystore_certificate_entry_name"
), certificate);
53
54
55
// Check the presence of PrivateKey in KeyStore
56
System.out.println(
"#### Check the presence of PrivateKey in KeyStore : entry="
+prop.getProperty(
"keystore_privatekey_entry_name"
)+
" and password="
+prop.getProperty(
"keystore_privatekey_entry_pwd"
));
57
boolean
isFound = keyStoreManagement.hasPrivateKey(prop.getProperty(
"keystore_privatekey_entry_name"
), prop.getProperty(
"keystore_privatekey_entry_pwd"
), privateKey.getEncoded());
58
System.out.println(
"=>"
+isFound);
59
60
61
// Get PrivateKey from KeyStore
62
System.out.println(
"#### Get PrivateKey from KeyStore : entry="
+prop.getProperty(
"keystore_privatekey_entry_name"
)+
" and password="
+prop.getProperty(
"keystore_privatekey_entry_pwd"
));
63
PrivateKey privateKeyExtract = keyStoreManagement.getPrivateKey(prop.getProperty(
"keystore_privatekey_entry_name"
), prop.getProperty(
"keystore_privatekey_entry_pwd"
));
64
System.out.println(
"#### Check the value of original PrivateKey and the extracted PrivateKey : "
);
65
System.out.println(
"=>"
+
new
String(privateKeyExtract.getEncoded()).equals(
new
String(privateKey.getEncoded())));
66
67
68
// Check the presence of Certificate in KeyStore
69
System.out.println(
"#### Check the presence of Certificate in KeyStore : entry="
+prop.getProperty(
"keystore_certificate_entry_name"
));
70
isFound = keyStoreManagement.hasCertificate(prop.getProperty(
"keystore_certificate_entry_name"
), certificate.getEncoded());
71
System.out.println(
"=>"
+isFound);
72
73
74
// Check the presence of PublicKey in KeyStore
75
System.out.println(
"#### Check the presence of PublicKey in KeyStore : entry="
+prop.getProperty(
"keystore_certificate_entry_name"
));
76
isFound = keyStoreManagement.hasPublicKeyOfCertificate(prop.getProperty(
"keystore_certificate_entry_name"
), publicKey.getEncoded());
77
System.out.println(
"=>"
+isFound);
78
79
// Get Certificate from KeyStore
80
System.out.println(
"#### Get Certificate from KeyStore : entry="
+prop.getProperty(
"keystore_certificate_entry_name"
));
81
Certificate certificateExtract = keyStoreManagement.getCertificate(prop.getProperty(
"keystore_certificate_entry_name"
));
82
System.out.println(
"#### Check the value of original Certificate and the extracted Certificate : "
);
83
System.out.println(
"=>"
+
new
String(certificateExtract.getEncoded()).equals(
new
String(certificate.getEncoded())));
84
85
// Get PublicKey from KeyStore
86
System.out.println(
"#### Get PublicKey from KeyStore : entry="
+prop.getProperty(
"keystore_certificate_entry_name"
));
87
PublicKey publicKeyExtract = keyStoreManagement.getPublicKeyOfCertificate(prop.getProperty(
"keystore_certificate_entry_name"
));
88
System.out.println(
"#### Check the value of original PublicKey and the extracted PublicKey : "
);
89
System.out.println(
"=>"
+
new
String(publicKeyExtract.getEncoded()).equals(
new
String(publicKey.getEncoded())));
The outputs should be:
########################## PRIVATE and PUBLIC KEY - RSA 1024
#### Generation of PrivateKey and PublicKey RSA 1024 via the use of JAVA classes
#### Generation of self signed certificate with previous PrivateKey and PublicKey RSA 1024
#### Check the value of original PublicKey and the PublicKey insided the Certificate:
=>true
#### Creation of Certificate Chain with the previous Certificate
#### Add PrivateKey to KeyStore : entry=KeyStoReP@sswd4PrivAteKEyeNtry and password=KeYp@sswdStorePrivATeEntryPwd
#### Add Certificate to KeyStore : entry=KeyStoReP@sswd4CertiFicaTeeNtry
#### Check the presence of PrivateKey in KeyStore : entry=KeyStoReP@sswd4PrivAteKEyeNtry and password=KeYp@sswdStorePrivATeEntryPwd
=>true
#### Get PrivateKey from KeyStore : entry=KeyStoReP@sswd4PrivAteKEyeNtry and password=KeYp@sswdStorePrivATeEntryPwd
#### Check the value of original PrivateKey and the extracted PrivateKey :
=>true
#### Check the presence of Certificate in KeyStore : entry=KeyStoReP@sswd4CertiFicaTeeNtry
=>true
#### Check the presence of PublicKey in KeyStore : entry=KeyStoReP@sswd4CertiFicaTeeNtry
=>true
#### Get Certificate from KeyStore : entry=KeyStoReP@sswd4CertiFicaTeeNtry
#### Check the value of original Certificate and the extracted Certificate :
=>true
#### Get PublicKey from KeyStore : entry=KeyStoReP@sswd4CertiFicaTeeNtry
#### Check the value of original PublicKey and the extracted PublicKey :
=>true
Resources:
https://en.wikipedia.org/wiki/X.509
https://docs.oracle.com/javase/7/docs/api/java/security/cert/Certificate.html
http://www.pixelstech.net/article/index.php?id=1406724116
http://www.pixelstech.net/article/1406726666-Generate-certificate-in-Java—-2
http://www.pixelstech.net/article/1408524957-Generate-cetrificate-in-Java—-3
Sources : keystore.zip
That’s all!!!
Huseyin OZVEREN