Example usage for java.security PrivateKey getAlgorithm

List of usage examples for java.security PrivateKey getAlgorithm

Introduction

In this page you can find the example usage for java.security PrivateKey getAlgorithm.

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

From source file:org.apache.cloudstack.network.ssl.CertServiceImpl.java

private void validateKeys(final PublicKey pubKey, final PrivateKey privKey) {
    Preconditions.checkNotNull(pubKey);//from  www. ja  va  2 s.  c o m
    Preconditions.checkNotNull(privKey);

    if (!pubKey.getAlgorithm().equals(privKey.getAlgorithm())) {
        throw new IllegalArgumentException("Public and private key have different algorithms");
    }

    // No encryption for DSA
    if (pubKey.getAlgorithm() != "RSA") {
        return;
    }

    try {
        final String data = "ENCRYPT_DATA";
        final SecureRandom random = new SecureRandom();
        final Cipher cipher = Cipher.getInstance(pubKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privKey, random);
        final byte[] encryptedData = cipher.doFinal(data.getBytes());

        cipher.init(Cipher.DECRYPT_MODE, pubKey, random);
        final String decreptedData = new String(cipher.doFinal(encryptedData));
        if (!decreptedData.equals(data)) {
            throw new IllegalStateException("Bad public-private key");
        }

    } catch (final BadPaddingException | IllegalBlockSizeException | InvalidKeyException
            | NoSuchPaddingException e) {
        throw new IllegalStateException("Bad public-private key", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalStateException("Invalid algorithm for public-private key", e);
    }
}

From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java

private PKIMessage buildCertBasedPKIProtection(PKIMessage pKIMessage, CMPCertificate[] extraCerts,
        PrivateKey key, String digestAlg, String provider, boolean verbose) throws NoSuchProviderException,
        NoSuchAlgorithmException, SecurityException, SignatureException, InvalidKeyException {
    // Select which signature algorithm we should use for the response, based on the digest algorithm and key type.
    ASN1ObjectIdentifier oid = AlgorithmTools.getSignAlgOidFromDigestAndKey(digestAlg, key.getAlgorithm());
    if (verbose) {
        log.info("Selected signature alg oid: " + oid.getId() + ", key algorithm: " + key.getAlgorithm());
    }/* w  w  w.j  av  a 2  s . com*/
    // According to PKCS#1 AlgorithmIdentifier for RSA-PKCS#1 has null Parameters, this means a DER Null (asn.1 encoding of null), not Java null.
    // For the RSA signature algorithms specified above RFC3447 states "...the parameters MUST be present and MUST be NULL."
    PKIHeaderBuilder headerBuilder = getHeaderBuilder(pKIMessage.getHeader());
    AlgorithmIdentifier pAlg = null;
    if ("RSA".equalsIgnoreCase(key.getAlgorithm())) {
        pAlg = new AlgorithmIdentifier(oid, DERNull.INSTANCE);
    } else {
        pAlg = new AlgorithmIdentifier(oid);
    }
    headerBuilder.setProtectionAlg(pAlg);
    // Most PKCS#11 providers don't like to be fed an OID as signature algorithm, so 
    // we use BC classes to translate it into a signature algorithm name instead
    PKIHeader head = headerBuilder.build();
    String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
    if (verbose) {
        log.info("Signing CMP message with signature alg: " + signatureAlgorithmName);
    }
    Signature sig = Signature.getInstance(signatureAlgorithmName, provider);
    sig.initSign(key);
    sig.update(getProtectedBytes(head, pKIMessage.getBody()));

    if ((extraCerts != null) && (extraCerts.length > 0)) {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()), extraCerts);
    } else {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()));
    }
    return pKIMessage;
}

From source file:org.digidoc4j.impl.BDocContainerTest.java

static byte[] getExternalSignature(Container container, final X509Certificate signerCert,
        SignedInfo prepareSigningSignature, final DigestAlgorithm digestAlgorithm) {
    Signer externalSigner = new ExternalSigner(signerCert) {
        @Override//from   www  . j  a  va2 s .c  om
        public byte[] sign(Container container, byte[] dataToSign) {
            try {
                KeyStore keyStore = KeyStore.getInstance("PKCS12");
                try (FileInputStream stream = new FileInputStream("testFiles/signout.p12")) {
                    keyStore.load(stream, "test".toCharArray());
                }
                PrivateKey privateKey = (PrivateKey) keyStore.getKey("1", "test".toCharArray());
                final String javaSignatureAlgorithm = "NONEwith" + privateKey.getAlgorithm();

                return DSSUtils.encrypt(javaSignatureAlgorithm, privateKey, addPadding(dataToSign));
            } catch (Exception e) {
                throw new DigiDoc4JException("Loading private key failed");
            }
        }

        private byte[] addPadding(byte[] digest) {
            byte[] signatureDigest;
            switch (digestAlgorithm) {
            case SHA512:
                signatureDigest = Constants.SHA512_DIGEST_INFO_PREFIX;
                break;
            case SHA256:
                signatureDigest = Constants.SHA256_DIGEST_INFO_PREFIX;
                break;
            default:
                throw new NotYetImplementedException();
            }
            return ArrayUtils.addAll(signatureDigest, digest);
        }
    };

    return externalSigner.sign(container, prepareSigningSignature.getDigest());
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Verifies that the supplied private key and signed certificate match by signing/verifying some test data.
 * /*from  ww  w  .  j a  v a2s  .c  om*/
 * @param privateKey A private key
 * @param cert the certificate
 * @throws ResourceException if the verification fails, or an error is encountered.
 */
protected void verify(PrivateKey privateKey, Certificate cert) throws ResourceException {
    PublicKey publicKey = cert.getPublicKey();
    byte[] data = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };
    boolean verified;
    try {
        Signature signer = Signature.getInstance(privateKey.getAlgorithm());
        signer.initSign(privateKey);
        signer.update(data);
        byte[] signed = signer.sign();
        Signature verifier = Signature.getInstance(publicKey.getAlgorithm());
        verifier.initVerify(publicKey);
        verifier.update(data);
        verified = verifier.verify(signed);
    } catch (Exception e) {
        throw new InternalServerErrorException("Error verifying private key and signed certificate", e);
    }
    if (!verified) {
        throw new BadRequestException("Private key does not match signed certificate");
    }
}

From source file:com.springcryptoutils.core.key.PrivateKeyRegistryByAliasImplTest.java

@Test
public void testPublicKeyRegistryIsProperlyLoaded() {
    assertNotNull(registryByAlias);//from www  .  j a  v  a 2  s  . c o m
    PrivateKey privateKey1 = registryByAlias.get(new KeyStoreChooser() {
        public String getKeyStoreName() {
            return "keystoreOne";
        }
    }, new PrivateKeyChooserByAlias() {
        public String getAlias() {
            return "test";
        }

        public String getPassword() {
            return "password";
        }
    });
    PrivateKey privateKey2 = registryByAlias.get(new KeyStoreChooser() {
        public String getKeyStoreName() {
            return "keystoreTwo";
        }
    }, new PrivateKeyChooserByAlias() {
        public String getAlias() {
            return "test";
        }

        public String getPassword() {
            return "password";
        }
    });
    assertNotNull(privateKey1);
    assertNotNull(privateKey2);
    assertEquals("algorithm", "RSA", privateKey1.getAlgorithm());
    assertEquals("algorithm", "RSA", privateKey2.getAlgorithm());
    assertNotSame(privateKey1, privateKey2);
}

From source file:com.android.builder.internal.packaging.sign.SignatureExtension.java

/**
 * Creates a new signature extension./* ww  w  .  ja v a 2 s  . co m*/
 *
 * @param manifestExtension the extension maintaining the manifest
 * @param minSdkVersion minSdkVersion of the package
 * @param certificate sign certificate
 * @param privateKey the private key to sign the jar
 * @param apkSignedHeaderValue value of the {@code X-Android-APK-Signed} header to output into
 * the {@code .SF} file or {@code null} if the header should not be output.
 *
 * @throws NoSuchAlgorithmException failed to obtain the digest algorithm.
 */
public SignatureExtension(@NonNull ManifestGenerationExtension manifestExtension, int minSdkVersion,
        @NonNull X509Certificate certificate, @NonNull PrivateKey privateKey,
        @Nullable String apkSignedHeaderValue) throws NoSuchAlgorithmException {
    mManifestExtension = manifestExtension;
    mSignatureFile = new Manifest();
    mDirty = false;
    mCertificate = certificate;
    mPrivateKey = privateKey;
    mApkSignedHeaderValue = apkSignedHeaderValue;

    mSignatureAlgorithm = SignatureAlgorithm.fromKeyAlgorithm(privateKey.getAlgorithm(), minSdkVersion);
    mDigestAlgorithm = DigestAlgorithm.findBest(minSdkVersion, mSignatureAlgorithm);
    mMessageDigest = MessageDigest.getInstance(mDigestAlgorithm.messageDigestName);
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

/**
 * Returns a signed certificate./*from  www .  j a v  a 2  s  .c o m*/
 *
 * @param builder
 *            builder to create the certificate
 * @param key
 *            private key for the certificate
 * @return a signed certificate
 * @throws OperatorCreationException
 *             if there was a problem creation a bouncy castle operator
 * @throws CertificateException
 *             if any of the certificates in the keystore could not be
 *             loaded
 */
private final X509Certificate getSignedCertificate(final X509v3CertificateBuilder builder, final PrivateKey key)
        throws OperatorCreationException, CertificateException {
    final ContentSigner signer; // Content signer
    final String provider; // Provider
    final X509Certificate signed; // Signed certificate

    provider = BouncyCastleProvider.PROVIDER_NAME;
    signer = new JcaContentSignerBuilder(getSignatureAlgorithm()).setProvider(provider).build(key);

    signed = new JcaX509CertificateConverter().setProvider(provider).getCertificate(builder.build(signer));

    LOGGER.debug("Signed certificate with {} private key {}, using algorithm {}", key.getAlgorithm(),
            Arrays.asList(key.getEncoded()), key.getFormat());

    return signed;
}

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Write the certificate file with a digital signature.
 *//*  w  w  w  .j av a  2 s  .  com*/
private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm())
            .build(privateKey);
    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    DEROutputStream dos = new DEROutputStream(mOutputJar);
    dos.writeObject(asn1.readObject());

    dos.flush();
    dos.close();
    asn1.close();
}

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

public String signQueryString(String queryString) throws SamlR2SignatureException {

    try {//from  w  w  w. j  a v a 2s.  c o m

        if (queryString == null || queryString.length() == 0) {
            logger.error("SAML 2.0 Qery string null");
            throw new SamlR2SignatureException("SAML 2.0 Qery string null");
        }

        if (logger.isDebugEnabled())
            logger.debug("Received SAML 2.0 Query string [" + queryString + "] for signing");

        PrivateKey privateKey = (PrivateKey) this.getKeyResolver().getPrivateKey();

        String keyAlgorithm = privateKey.getAlgorithm();
        Signature signature = null;
        String algURI = null;
        if (keyAlgorithm.equals("RSA")) {
            signature = Signature.getInstance(SHA1_WITH_RSA);
            algURI = SignatureMethod.RSA_SHA1;
        } else if (keyAlgorithm.equals("DSA")) {
            signature = Signature.getInstance(SHA1_WITH_DSA);
            algURI = SignatureMethod.DSA_SHA1;
        } else {
            throw new SamlR2SignatureException(
                    "SAML 2.0 Signature does not support provided key's algorithm " + keyAlgorithm);
        }

        if (queryString.charAt(queryString.length() - 1) != '&') {
            queryString = queryString + "&";
        }

        queryString += "SigAlg=" + URLEncoder.encode(algURI, "UTF-8");

        if (logger.isTraceEnabled())
            logger.trace("Signing SAML 2.0 Query string [" + queryString + "]");

        signature.initSign(privateKey);
        signature.update(queryString.getBytes());
        byte[] sigBytes = null;
        sigBytes = signature.sign();
        if (sigBytes == null || sigBytes.length == 0) {
            logger.error("Cannot generate signed query string, Signature created 'null' value.");
            throw new SamlR2SignatureException(
                    "Cannot generate signed query string, Signature created 'null' value.");
        }

        Base64 encoder = new Base64();
        String encodedSig = new String(encoder.encode(sigBytes), "UTF-8");
        queryString += "&Signature=" + URLEncoder.encode(encodedSig, "UTF-8");

        if (logger.isTraceEnabled())
            logger.trace("Signed SAML 2.0 Query string [" + queryString + "]");

        return queryString;
    } catch (Exception e) {
        throw new SamlR2SignatureException("Error generating SAML 2.0 Query string signature " + e.getMessage(),
                e);
    }
}

From source file:com.gamesalutes.utils.EncryptUtils.java

/**
 * Creates an <code>SSLContext</code> that uses the specified trusted certificates.
 * //w ww  .j av  a2 s . co m
 * @param protocol the {@link TransportSecurityProtocol} to use for the context
 * @param trustedCerts certificates to import into the <code>SSLContext</code> or <code>null</code>
 *         to accept all issuers
 * @param privateKey the client key to authenticate the client with the server
 * @return the created <code>SSLContext</code>
 * @throws Exception if error occurs during the process of creating the context
 */
public static SSLContext createSSLContext(TransportSecurityProtocol protocol, PrivateKey privateKey,
        java.security.cert.X509Certificate... trustedCerts) throws Exception {
    if (trustedCerts != null && trustedCerts.length == 0)
        throw new IllegalArgumentException("trustedCerts is empty");

    X509TrustManager defaultManager = null;
    KeyManager[] keyManagers = null;
    KeyStore keyStore = null;

    if (privateKey != null || trustedCerts != null) {
        // create a new key store instance that will install the certificates
        // and/or the private keys
        keyStore = KeyStore.getInstance(JKS_TYPE);
        keyStore.load(null, null);
    }

    // import the certs
    if (trustedCerts != null) {
        // set up the key manager for the certificates
        javax.net.ssl.TrustManagerFactory trustFact = javax.net.ssl.TrustManagerFactory
                .getInstance(KEY_MANAGEMENT_ALG_SUN_X509);

        // install the certificates in the key store and give them a unique alias
        int imported = 0;
        for (java.security.cert.X509Certificate cert : trustedCerts) {
            if (cert != null)
                keyStore.setCertificateEntry("cert" + ++imported, cert);
        }
        if (imported == 0)
            throw new IllegalArgumentException("no non-null certs in trustedCerts");
        // add the certs to the trust factory
        trustFact.init(keyStore);

        // get a default trust manager
        TrustManager[] tms = trustFact.getTrustManagers();
        if (tms != null && tms.length >= 1)
            defaultManager = (X509TrustManager) tms[0];
    }

    // import the private key
    if (privateKey != null) {
        keyStore.setKeyEntry("client", privateKey, null, null);
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(privateKey.getAlgorithm());

        kmfactory.init(keyStore, null);
        keyManagers = kmfactory.getKeyManagers();
    }
    //create the SSL context based on these parameters
    SSLContext sslContext = SSLContext.getInstance(protocol.toString());

    // use a CertX509TrustManager since default one will still fail validation for 
    // self-signed certs
    sslContext.init(keyManagers,
            new TrustManager[] { trustedCerts != null ? new CertX509TrustManager(defaultManager, trustedCerts)
                    : new CertX509TrustManager() },
            null);

    return sslContext;

}