Search in sources :

Example 76 with Key

use of java.security.Key in project jdk8u_jdk by JetBrains.

the class SignatureTest method main.

public static void main(String[] args) throws Exception {
    String testAlg = args[0];
    int testSize = Integer.parseInt(args[1]);
    byte[] data = new byte[100];
    RandomFactory.getRandom().nextBytes(data);
    // create a key pair
    KeyPair kpair = generateKeys(KEYALG, testSize);
    Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());
    Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());
    // For signature algorithm, create and verify a signature
    Arrays.stream(privs).forEach(priv -> Arrays.stream(pubs).forEach(pub -> {
        try {
            checkSignature(data, (PublicKey) pub, (PrivateKey) priv, testAlg);
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException ex) {
            throw new RuntimeException(ex);
        }
    }));
}
Also used : KeyPairGenerator(java.security.KeyPairGenerator) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SignatureException(java.security.SignatureException) Signature(java.security.Signature) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeyFactory(java.security.KeyFactory) Key(java.security.Key) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) PUBLIC_KEY(javax.crypto.Cipher.PUBLIC_KEY) RSAPublicKey(java.security.interfaces.RSAPublicKey) RandomFactory(jdk.testlibrary.RandomFactory) PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) InvalidKeyException(java.security.InvalidKeyException) PRIVATE_KEY(javax.crypto.Cipher.PRIVATE_KEY) NoSuchProviderException(java.security.NoSuchProviderException) KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) RSAPublicKey(java.security.interfaces.RSAPublicKey) PrivateKey(java.security.PrivateKey)

Example 77 with Key

use of java.security.Key in project jdk8u_jdk by JetBrains.

the class RSAEncryptDecrypt method main.

public static void main(String[] args) throws Exception {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SunMSCAPI");
    KeyPair keyPair = generator.generateKeyPair();
    Key publicKey = keyPair.getPublic();
    Key privateKey = keyPair.getPrivate();
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("RSA", "SunMSCAPI");
    } catch (GeneralSecurityException e) {
        System.out.println("Cipher not supported by provider, skipping...");
        return;
    }
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    displayBytes("Plaintext data:", PLAINTEXT);
    byte[] data = cipher.doFinal(PLAINTEXT);
    displayBytes("Encrypted data:", data);
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    data = cipher.doFinal(data);
    displayBytes("Decrypted data:", data);
}
Also used : KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) KeyPairGenerator(java.security.KeyPairGenerator) Cipher(javax.crypto.Cipher) Key(java.security.Key)

Example 78 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class CertificatesController method toCertDataFormat.

/*
	 * Converts an incoming P12 format to an appropriate format to be store in the config store.  If a keystore protection manager
	 * has been configured, then the private key is wrapped before sending to the config store.
	 */
private byte[] toCertDataFormat(byte[] certOrP12Bytes, byte[] privateKeyBytes, PrivateKeyType privKeyType) throws CryptoException {
    try {
        // if there is no private key, then just return the encoded certificate
        if (privKeyType == PrivateKeyType.NONE)
            return certOrP12Bytes;
        final CertContainer cont = CertUtils.toCertContainer(certOrP12Bytes);
        // if this is a PKCS12 format, then either return the bytes as is, or if there is keystore manager, wrap the private keys
        if (privKeyType == PrivateKeyType.PKCS_12_PASSPHRASE | privKeyType == PrivateKeyType.PKCS_12_UNPROTECTED) {
            // as PKCS12 file
            if (this.keyManager == null) {
                this.log.info("Storing PKCS12 file in PKCS12 unprotected format");
                return certOrP12Bytes;
            } else {
                this.log.info("Storing PKCS12 file in wrapped format");
                // now wrap the private key
                final byte[] wrappedKey = this.keyManager.wrapWithSecretKey((SecretKey) ((KeyStoreProtectionManager) keyManager).getPrivateKeyProtectionKey(), cont.getKey());
                // return the wrapped key format
                return CertUtils.certAndWrappedKeyToRawByteFormat(wrappedKey, cont.getCert());
            }
        } else // when there is private key file, then either turn into a PKCS12 file (if there is no key manager), or wrap the key.
        {
            // cert and wrapped key format
            if (privKeyType == PrivateKeyType.PKCS8_WRAPPED) {
                this.log.info("Storing already wrapped PKCS8 file");
                return CertUtils.certAndWrappedKeyToRawByteFormat(privateKeyBytes, cont.getCert());
            }
            // get a private key object, the private key is normalized at this point into an unencrypted format
            final KeyFactory kf = KeyFactory.getInstance("RSA", CertUtils.getJCEProviderName());
            final PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(privateKeyBytes);
            final Key privKey = kf.generatePrivate(keysp);
            if (this.keyManager == null) {
                this.log.info("Storing PKCS8 private key in PKCS12 unprotected format");
                // if there is no keystore manager, we can't wrap the keys, so we'll just send them over the wire
                // as PKCS12 file.  need to turn this into a PKCS12 format
                final KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CertUtils.getJCEProviderName());
                localKeyStore.load(null, null);
                localKeyStore.setKeyEntry("privCert", privKey, "".toCharArray(), new java.security.cert.Certificate[] { cont.getCert() });
                final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
                localKeyStore.store(outStr, "".toCharArray());
                try {
                    return outStr.toByteArray();
                } finally {
                    IOUtils.closeQuietly(outStr);
                }
            } else {
                this.log.info("Storing PKCS8 private key in wrapped format");
                // wrap the key and turn the stream in the wrapped key format
                final byte[] wrappedKey = this.keyManager.wrapWithSecretKey((SecretKey) ((KeyStoreProtectionManager) keyManager).getPrivateKeyProtectionKey(), privKey);
                return CertUtils.certAndWrappedKeyToRawByteFormat(wrappedKey, cont.getCert());
            }
        }
    } catch (Exception e) {
        throw new CryptoException("Failed to conver certificate and key to cert data format: " + e.getMessage(), e);
    }
}
Also used : PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) KeyStoreProtectionManager(org.nhindirect.common.crypto.KeyStoreProtectionManager) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException) KeyStore(java.security.KeyStore) CertContainer(org.nhindirect.config.model.utils.CertUtils.CertContainer) KeyFactory(java.security.KeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) IOException(java.io.IOException) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException)

Example 79 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class DNSController method toCertContainer.

public CertContainer toCertContainer(byte[] data) throws Exception {
    CertContainer certContainer = null;
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        // lets try this a as a PKCS12 data stream first
        try {
            final KeyStore localKeyStore = KeyStore.getInstance("PKCS12", getJCEProviderName());
            localKeyStore.load(bais, "".toCharArray());
            final Enumeration<String> aliases = localKeyStore.aliases();
            // we are really expecting only one alias
            if (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) localKeyStore.getCertificate(alias);
                // check if there is private key
                final Key key = localKeyStore.getKey(alias, "".toCharArray());
                if (key != null && key instanceof PrivateKey) {
                    certContainer = new CertContainer(cert, key);
                }
            }
        } catch (Exception e) {
        // must not be a PKCS12 stream, go on to next step
        }
        if (certContainer == null) {
            //try X509 certificate factory next
            bais.reset();
            bais = new ByteArrayInputStream(data);
            X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais);
            certContainer = new CertContainer(cert, null);
        }
        bais.close();
    } catch (Exception e) {
        throw new ConfigurationServiceException("Data cannot be converted to a valid X.509 Certificate", e);
    }
    return certContainer;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) ConfigurationServiceException(org.nhindirect.config.service.ConfigurationServiceException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) CertificateEncodingException(javax.security.cert.CertificateEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) TextParseException(org.xbill.DNS.TextParseException) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) IOException(java.io.IOException) ConfigurationServiceException(org.nhindirect.config.service.ConfigurationServiceException)

Example 80 with Key

use of java.security.Key in project nhin-d by DirectProject.

the class CertificateServiceImpl method toCertContainer.

public CertContainer toCertContainer(byte[] data) throws ConfigurationServiceException {
    CertContainer certContainer = null;
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        // lets try this a as a PKCS12 data stream first
        try {
            KeyStore localKeyStore = KeyStore.getInstance("PKCS12", Certificate.getJCEProviderName());
            localKeyStore.load(bais, "".toCharArray());
            Enumeration<String> aliases = localKeyStore.aliases();
            // we are really expecting only one alias 
            if (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) localKeyStore.getCertificate(alias);
                // check if there is private key
                Key key = localKeyStore.getKey(alias, "".toCharArray());
                if (key != null && key instanceof PrivateKey) {
                    certContainer = new CertContainer(cert, key);
                }
            }
        } catch (Exception e) {
        // must not be a PKCS12 stream, go on to next step
        }
        if (certContainer == null) {
            //try X509 certificate factory next       
            bais.reset();
            bais = new ByteArrayInputStream(data);
            X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais);
            certContainer = new CertContainer(cert, null);
        }
        bais.close();
    } catch (Exception e) {
        throw new ConfigurationServiceException("Data cannot be converted to a valid X.509 Certificate", e);
    }
    return certContainer;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) ConfigurationServiceException(org.nhindirect.config.service.ConfigurationServiceException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) CertificateParsingException(java.security.cert.CertificateParsingException) ConfigurationServiceException(org.nhindirect.config.service.ConfigurationServiceException)

Aggregations

Key (java.security.Key)302 PrivateKey (java.security.PrivateKey)112 SecretKey (javax.crypto.SecretKey)83 KeyStore (java.security.KeyStore)64 PublicKey (java.security.PublicKey)62 Cipher (javax.crypto.Cipher)60 X509Certificate (java.security.cert.X509Certificate)57 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)50 Test (org.junit.Test)44 IOException (java.io.IOException)42 ByteArrayInputStream (java.io.ByteArrayInputStream)38 Certificate (java.security.cert.Certificate)36 SecretKeySpec (javax.crypto.spec.SecretKeySpec)36 KeyFactory (java.security.KeyFactory)35 InvalidKeyException (java.security.InvalidKeyException)32 KeyGenerator (javax.crypto.KeyGenerator)32 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)26 KeyStoreException (java.security.KeyStoreException)22 SecureRandom (java.security.SecureRandom)21 IvParameterSpec (javax.crypto.spec.IvParameterSpec)21