Search in sources :

Example 66 with RSAPrivateKeySpec

use of java.security.spec.RSAPrivateKeySpec in project Terasology by MovingBlocks.

the class PrivateIdentityCertificate method sign.

/**
 * Produces a signature for data that can be verified as by the paired public certificate.
 *
 * @param dataToSign
 * @return The signature
 */
public byte[] sign(byte[] dataToSign) {
    RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(modulus, exponent);
    Signature signer = null;
    try {
        signer = Signature.getInstance(IdentityConstants.SIGNATURE_ALGORITHM);
        KeyFactory keyFactory = KeyFactory.getInstance(IdentityConstants.CERTIFICATE_ALGORITHM);
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        signer.initSign(key, new SecureRandom());
        signer.update(dataToSign);
        return signer.sign();
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | SignatureException e) {
        throw new RuntimeException("Unexpected exception during signing", e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) Signature(java.security.Signature) SecureRandom(java.security.SecureRandom) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) KeyFactory(java.security.KeyFactory)

Example 67 with RSAPrivateKeySpec

use of java.security.spec.RSAPrivateKeySpec in project tbd-studio-se by Talend.

the class MongoDBConnectionUtil method buildSSLContext_PEM.

private static SSLContext buildSSLContext_PEM(String _keystore, String _keystorePass, String _truststore, String _truststorePass, SSLContext sslContext) {
    SSLContext context = null;
    final String pubCertEndDelimiter = "-----END CERTIFICATE-----";
    final String privateKeyStartDelimiter = "-----BEGIN PRIVATE KEY-----";
    final String privateKeyEndDelimiter = "-----END PRIVATE KEY-----";
    final String privateKeyRSAStartDelimiter = "-----BEGIN RSA PRIVATE KEY-----";
    final String privateKeyRSAEndDelimiter = "-----END RSA PRIVATE KEY-----";
    try {
        context = SSLContext.getInstance("TLS");
        byte[] certAndKey = Files.readAllBytes(Paths.get(new File(_keystore).toURI()));
        String[] tokens = new String(certAndKey).split(pubCertEndDelimiter);
        byte[] certBytes = tokens[0].concat(pubCertEndDelimiter).getBytes();
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        java.security.cert.Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(certBytes));
        // 
        X509Certificate cert = (X509Certificate) certificate;
        PrivateKey key = null;
        KeyFactory kf = KeyFactory.getInstance("RSA");
        if (tokens[1].contains(privateKeyStartDelimiter)) {
            byte[] privatekeyBytes = tokens[1].replace(privateKeyStartDelimiter, "").replace(privateKeyEndDelimiter, "").replace("\r\n", "").replace("\n", "").getBytes();
            byte[] decode = Base64.getDecoder().decode(privatekeyBytes);
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decode);
            key = kf.generatePrivate(spec);
        } else if (tokens[1].contains(privateKeyRSAStartDelimiter)) {
            byte[] privateKeyBytes = tokens[1].replace(privateKeyRSAStartDelimiter, "").replace(privateKeyRSAEndDelimiter, "").replace("\r\n", "").replace("\n", "").getBytes("UTF-8");
            byte[] decodeBytes = Base64.getDecoder().decode(privateKeyBytes);
            ASN1Object fromByteArray = ASN1Sequence.fromByteArray(decodeBytes);
            RSAPrivateKeyStructure asn1PrivKey = new RSAPrivateKeyStructure((ASN1Sequence) fromByteArray);
            RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());
            key = kf.generatePrivate(rsaPrivKeySpec);
        }
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(null);
        keystore.setCertificateEntry("cert-alias", cert);
        keystore.setKeyEntry("key-alias", key, "changeit".toCharArray(), new Certificate[] { cert });
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keystore, "changeit".toCharArray());
        KeyManager[] km = kmf.getKeyManagers();
        context.init(km, null, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return context;
}
Also used : PrivateKey(java.security.PrivateKey) SSLContext(javax.net.ssl.SSLContext) CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) NoSQLReflectionException(org.talend.repository.nosql.exceptions.NoSQLReflectionException) NoSQLServerException(org.talend.repository.nosql.exceptions.NoSQLServerException) JSONException(org.talend.utils.json.JSONException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) Certificate(java.security.cert.Certificate) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) RSAPrivateKeyStructure(org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) ASN1Object(org.bouncycastle.asn1.ASN1Object) File(java.io.File) KeyManager(javax.net.ssl.KeyManager) KeyFactory(java.security.KeyFactory)

Example 68 with RSAPrivateKeySpec

use of java.security.spec.RSAPrivateKeySpec in project Mycat-Server by MyCATApache.

the class DecryptUtil method decrypt.

public static String decrypt(PublicKey publicKey, String cipherText) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    try {
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
    } catch (InvalidKeyException e) {
        // 因为 IBM JDK 不支持私钥加密, 公钥解密, 所以要反转公私钥
        // 也就是说对于解密, 可以通过公钥的参数伪造一个私钥对象欺骗 IBM JDK
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
        Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
        // It is a stateful object. so we need to get new one.
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey);
    }
    if (cipherText == null || cipherText.length() == 0) {
        return cipherText;
    }
    byte[] cipherBytes = Base64.base64ToByteArray(cipherText);
    byte[] plainBytes = cipher.doFinal(cipherBytes);
    return new String(plainBytes);
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) Cipher(javax.crypto.Cipher) InvalidKeyException(java.security.InvalidKeyException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) RSAPublicKey(java.security.interfaces.RSAPublicKey) PrivateKey(java.security.PrivateKey)

Example 69 with RSAPrivateKeySpec

use of java.security.spec.RSAPrivateKeySpec in project j2objc by google.

the class IosRSAKeyFactory method engineGetKeySpec.

@Override
@SuppressWarnings("unchecked")
protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec) throws InvalidKeySpecException {
    if (key == null) {
        throw new InvalidKeySpecException("key == null");
    }
    if (keySpec == null) {
        throw new InvalidKeySpecException("keySpec == null");
    }
    if (!"RSA".equals(key.getAlgorithm())) {
        throw new InvalidKeySpecException("Key must be a RSA key");
    }
    if (key instanceof RSAPublicKey && RSAPublicKeySpec.class.isAssignableFrom(keySpec)) {
        RSAPublicKey rsaKey = (RSAPublicKey) key;
        return (T) new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());
    } else if (key instanceof PublicKey && RSAPublicKeySpec.class.isAssignableFrom(keySpec)) {
        final byte[] encoded = key.getEncoded();
        if (!"X.509".equals(key.getFormat()) || encoded == null) {
            throw new InvalidKeySpecException("Not a valid X.509 encoding");
        }
        RSAPublicKey rsaKey = (RSAPublicKey) engineGeneratePublic(new X509EncodedKeySpec(encoded));
        return (T) new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());
    } else if (key instanceof RSAPrivateCrtKey && RSAPrivateCrtKeySpec.class.isAssignableFrom(keySpec)) {
        RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
        return (T) new RSAPrivateCrtKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent(), rsaKey.getPrivateExponent(), rsaKey.getPrimeP(), rsaKey.getPrimeQ(), rsaKey.getPrimeExponentP(), rsaKey.getPrimeExponentQ(), rsaKey.getCrtCoefficient());
    } else if (key instanceof RSAPrivateCrtKey && RSAPrivateKeySpec.class.isAssignableFrom(keySpec)) {
        RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
        return (T) new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent());
    } else if (key instanceof RSAPrivateKey && RSAPrivateKeySpec.class.isAssignableFrom(keySpec)) {
        RSAPrivateKey rsaKey = (RSAPrivateKey) key;
        return (T) new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent());
    } else if (key instanceof PrivateKey && RSAPrivateCrtKeySpec.class.isAssignableFrom(keySpec)) {
        final byte[] encoded = key.getEncoded();
        if (!"PKCS#8".equals(key.getFormat()) || encoded == null) {
            throw new InvalidKeySpecException("Not a valid PKCS#8 encoding");
        }
        RSAPrivateKey privKey = (RSAPrivateKey) engineGeneratePrivate(new PKCS8EncodedKeySpec(encoded));
        if (privKey instanceof RSAPrivateCrtKey) {
            RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) privKey;
            return (T) new RSAPrivateCrtKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent(), rsaKey.getPrivateExponent(), rsaKey.getPrimeP(), rsaKey.getPrimeQ(), rsaKey.getPrimeExponentP(), rsaKey.getPrimeExponentQ(), rsaKey.getCrtCoefficient());
        } else {
            throw new InvalidKeySpecException("Encoded key is not an RSAPrivateCrtKey");
        }
    } else if (key instanceof PrivateKey && RSAPrivateKeySpec.class.isAssignableFrom(keySpec)) {
        final byte[] encoded = key.getEncoded();
        if (!"PKCS#8".equals(key.getFormat()) || encoded == null) {
            throw new InvalidKeySpecException("Not a valid PKCS#8 encoding");
        }
        RSAPrivateKey rsaKey = (RSAPrivateKey) engineGeneratePrivate(new PKCS8EncodedKeySpec(encoded));
        return (T) new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent());
    } else if (key instanceof PrivateKey && PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) {
        final byte[] encoded = key.getEncoded();
        if (!"PKCS#8".equals(key.getFormat())) {
            throw new InvalidKeySpecException("Encoding type must be PKCS#8; was " + key.getFormat());
        } else if (encoded == null) {
            throw new InvalidKeySpecException("Key is not encodable");
        }
        return (T) new PKCS8EncodedKeySpec(encoded);
    } else if (key instanceof PublicKey && X509EncodedKeySpec.class.isAssignableFrom(keySpec)) {
        final byte[] encoded = key.getEncoded();
        if (!"X.509".equals(key.getFormat())) {
            throw new InvalidKeySpecException("Encoding type must be X.509; was " + key.getFormat());
        } else if (encoded == null) {
            throw new InvalidKeySpecException("Key is not encodable");
        }
        return (T) new X509EncodedKeySpec(encoded);
    } else {
        throw new InvalidKeySpecException("Unsupported key type and key spec combination; key=" + key.getClass().getName() + ", keySpec=" + keySpec.getName());
    }
}
Also used : RSAPrivateCrtKeySpec(java.security.spec.RSAPrivateCrtKeySpec) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey)

Example 70 with RSAPrivateKeySpec

use of java.security.spec.RSAPrivateKeySpec in project j2objc by google.

the class IosRSAKeyFactory method engineTranslateKey.

@Override
protected Key engineTranslateKey(Key key) throws InvalidKeyException {
    if (key == null) {
        throw new InvalidKeyException("key == null");
    }
    if ((key instanceof IosRSAKey.IosRSAPublicKey) || (key instanceof IosRSAKey.IosRSAPrivateKey)) {
        return key;
    } else if (key instanceof RSAPublicKey) {
        RSAPublicKey rsaKey = (RSAPublicKey) key;
        try {
            return engineGeneratePublic(new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent()));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if (key instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
        BigInteger modulus = rsaKey.getModulus();
        BigInteger publicExponent = rsaKey.getPublicExponent();
        BigInteger privateExponent = rsaKey.getPrivateExponent();
        BigInteger primeP = rsaKey.getPrimeP();
        BigInteger primeQ = rsaKey.getPrimeQ();
        BigInteger primeExponentP = rsaKey.getPrimeExponentP();
        BigInteger primeExponentQ = rsaKey.getPrimeExponentQ();
        BigInteger crtCoefficient = rsaKey.getCrtCoefficient();
        try {
            return engineGeneratePrivate(new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponentQ, crtCoefficient));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if (key instanceof RSAPrivateKey) {
        RSAPrivateKey rsaKey = (RSAPrivateKey) key;
        BigInteger modulus = rsaKey.getModulus();
        BigInteger privateExponent = rsaKey.getPrivateExponent();
        try {
            return engineGeneratePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if ((key instanceof PrivateKey) && ("PKCS#8".equals(key.getFormat()))) {
        byte[] encoded = key.getEncoded();
        if (encoded == null) {
            throw new InvalidKeyException("Key does not support encoding");
        }
        try {
            return engineGeneratePrivate(new PKCS8EncodedKeySpec(encoded));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if ((key instanceof PublicKey) && ("X.509".equals(key.getFormat()))) {
        byte[] encoded = key.getEncoded();
        if (encoded == null) {
            throw new InvalidKeyException("Key does not support encoding");
        }
        try {
            return engineGeneratePublic(new X509EncodedKeySpec(encoded));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else {
        throw new InvalidKeyException("Key must be an RSA public or private key; was " + key.getClass().getName());
    }
}
Also used : RSAPrivateCrtKeySpec(java.security.spec.RSAPrivateCrtKeySpec) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) InvalidKeyException(java.security.InvalidKeyException) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BigInteger(java.math.BigInteger) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey)

Aggregations

RSAPrivateKeySpec (java.security.spec.RSAPrivateKeySpec)78 KeyFactory (java.security.KeyFactory)49 PrivateKey (java.security.PrivateKey)41 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)30 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)27 BigInteger (java.math.BigInteger)25 PublicKey (java.security.PublicKey)19 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)17 InvalidKeyException (java.security.InvalidKeyException)14 Cipher (javax.crypto.Cipher)14 RSAPublicKey (java.security.interfaces.RSAPublicKey)13 Signature (java.security.Signature)12 KeyPair (java.security.KeyPair)10 KeySpec (java.security.spec.KeySpec)10 SecretKeyFactory (javax.crypto.SecretKeyFactory)9 IOException (java.io.IOException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 SignatureException (java.security.SignatureException)8 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)7 SecureRandom (java.security.SecureRandom)6