22 Mayıs 2019 Çarşamba

KeyStore Sınıfı

Giriş
Şu satırları dahil ederiz.
import java.security.KeyStore;
import java.security.KeyStore.Entry;
Neden Lazım
Normalde şöyle yapabiliriz. Ancak burada public-private key bellekte ve diskte saklanmıyor.
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
keyGen.initialize(2048, random);
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
Keyleri güvenli bir yerde saklamak için şöyle yaparız
KeyStore keyStore = KeyStore.getInstance("PKCS12");
char[] password = "secret".toCharArray();
keyStore.load(new FileInputStream("keystore.p12"), password);
PrivateKey privateKey = (PrivateKey) keyStore.getKey("mykey", password);
PublicKey publicKey = keyStore.getCertificate("mykey").getPublicKey();
Örnek - SunX509
Bu sınıf SSLContext yaratmak için kullanılır. Şöyle yaparız.
//Returns keystore object in definied type, here jks
KeyStore keyStore = KeyStore.getInstance("JKS");
//loads the keystore from givin input stream, and the password to unclock jks
keyStore.load(new FileInputStream("x509-ca.jks"), "password".toCharArray());

// Create key manager
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, "password".toCharArray());
KeyManager[] km = keyManagerFactory.getKeyManagers();

// Create trust manager
TrustManagerFactory trustManagerFactory = TrustManagerFactory.
  getInstance("SunX509");
trustManagerFactory.init(keyStore);
TrustManager[] tm = trustManagerFactory.getTrustManagers();

// opens a secure socket with definied protocol
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");

sslContext.init(km, tm, null);
Nested Sınıflar
Açıklaması şöyle
A KeyStore manages different types of entries. Each entry in a keystore is identified by an “alias” string. Each type of entry implements the KeyStore.Entry interface. Three basic KeyStore.Entry implementations are provided:
Bunlar şöyle
public static final class PrivateKeyEntry implements Entry {
  private final PrivateKey privKey;
  private final Certificate[] chain;
  private final Set<Attribute> attributes;
  ...
}

public static final class SecretKeyEntry implements Entry {
  private final SecretKey sKey;
  private final Set<Attribute> attributes;
  ...
}
public static final class TrustedCertificateEntry implements Entry {
  private final Certificate cert;
  private final Set<Attribute> attributes;
  ...
}
Açıklaması şöyle
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.

aliases metodu
Alias'ları dolaşmak için şöyle yaparız.
Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements()) {
 String sAlias = aliases.nextElement();
}
İlk alias'ı almak için şöyle yaparız.
String alias = ks.aliases().nextElement();
getCertificate metodu
Alias'ını bildiğimiz bir sertifkaya erişmek için şöyle yaparız.
String alias = ...;
Certificate c = ks.getCertificate (alias);
Certificate arayüzü X509Certificate kullanmak için şöyle yaparız.
String alias = ...;
X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
getCertificateChain metodu
Şöyle yaparız.
String alias = ...;
Certificate[] chain = ks.getCertificateChain(aliasKey);
System.out.println("---> chain length: " + chain.length);
for (Certificate cert: chain) {
  System.out.println(cert);
}
getInstance metodu - type
Bir liste şöyle
- JKS : Java KeyStore. Oracle's KeyStore format.
- JCEKS : Java Cryptography Extension KeyStore. More secure version of JKS.
- PKCS #12 : Public-Key Cryptography Standards #12 KeyStore. RSA's KeyStore format.
- BKS :Bouncy Castle KeyStore. Bouncy Castle's version of JKS.
- BKS-V1 : Bouncy Castle KeyStore (older version).
- UBER : Bouncy Castle UBER KeyStore. More secure version of BKS.
- BCFKS : Bouncy Castle FIPS KeyStore (uses FIPS compliant algorithms PBDKF2, SHA-512 and AES CCM).
Açıklaması şöyle.
JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.
JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.
PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.
PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.
1. JKS
Default tip JKS olup şöyle alınır.
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
veya şöyle yaparız.
KeyStore ks = KeyStore.getInstance("JKS");
2. JCEKS
JCKES, JKS'nin iyileştirilmiş hali. Şöyle yapabiliriz.
KeyStore ks = KeyStore.getInstance("JCEKS");
3. PKCS12
Diğer programlama dilleri ile de kullanılabilir. Açıklaması şöyle
PKCS12, this is a standard keystore type which cab be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.
Şöyle yaparz.
KeyStore ks = KeyStore.getInstance("PKCS12");
4. Windows - My (personal certificate store)
Şöyle yaparız.
KeyStore ks = KeyStore.getInstance("Windows-MY");
Provider kullanmak istersek şöyle yaparız.
// load the Windows keystore
KeyStore ks = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
getEntry metodu
Şöyle yaparız.
char[] keyStorePassword = ...;
String alias = ...;
KeyStore.Entry entry = ks.getEntry(alias, new KeyStore.PasswordProtection(
                keyStorePassword));
Alınan nesne başka bir şeye cast edilebilir.
KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) entry;
getKey metodu
Alias'ı olan bir private key nesnesini almak için şöyle yaparız. Bu key Cipher nesnesine geçilerek public key ile şifrelenmiş veri açılabilir.
PrivateKey key = (PrivateKey)ks.getKey(aliasname, password);
isKeyEntry metodu
Nesnenin Key ile korunan bir sertifika olup olmadığını döner.
Örnek
Alias'ını bildiğimiz bir girdiyi kontrol etmek için şöyle yaparız.
String alias = ...
if (ks.isKeyEntry(alias)) {...}
load metodu
Windows için şöyle yaparız.
KeyStore ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null) ;
load metodu
Dosyayı yüklemek için dosya yolu ve eğer varsa şifre sağlanır. Şifre char[] şeklinde sağlanmalıdır. Keystore şifresi keytool komutunun "-storepass" seçeneği ile verilebilir. Eğer Keystore yaratılırken şifre verilmemişse null geçilir.

FileInputStream ile şöyle yapılır.
char[] password = ...;

java.io.FileInputStream fis = null;
try {
    fis = new java.io.FileInputStream("keyStoreName");
    ks.load(fis, password);
} finally {
    if (fis != null) {
        fis.close();
    }
}
FileInputStream kullanan bir başka örnek şöyle
FileInputStream in = new FileInputStream("<path to your key store>");
ks.load(in, "password".toCharArray);
in.close();
setEntry metodu - string + Key + Certificate
Key ile korunan bir sertifika ekler.
Örnek
Sertifika eklemek istersek şöyle yaparız.
Certificate c = CertificateFactory.getInstance("X.509").
  ..generateCertificate(new FileInputStream("C:/Users/me/Downloads/myca.crt"));
KeyStore.TrustedCertificateEntry entry = new KeyStore.TrustedCertificateEntry(c);
ks.setEntry("CA1", entry , null);
Örnek
Sertifika zincirini başka bir KeyStore'a kopyalamak için şöyle yaparız.
Key key = keystore.getKey(keyAlias, clientKeyStorePassPhrase);
Certificate[] chain = keystore.getCertificateChain(keyAlias);
server.keystore.setKeyEntry(keyAlias, key, serverKeyStorePassPhrase, chain);

Hiç yorum yok:

Yorum Gönder