Example usage for java.security PublicKey getAlgorithm

List of usage examples for java.security PublicKey getAlgorithm

Introduction

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

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    MainClass kpge = new MainClass();
    KeyPair kp = kpge.generateKeyPair(999);
    System.out.println("-- Public Key ----");
    PublicKey pubKey = kp.getPublic();
    System.out.println("   Algorithm=" + pubKey.getAlgorithm());
    System.out.println("   Encoded=" + pubKey.getEncoded());
    System.out.println("   Format=" + pubKey.getFormat());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    keyGen.initialize(1024);/* w w  w  . j  a v  a  2 s . co m*/
    KeyPair keypair = keyGen.genKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();

    Serializable o = new MyClass();
    Signature sig = Signature.getInstance(privateKey.getAlgorithm());
    SignedObject so = new SignedObject(o, privateKey, sig);

    sig = Signature.getInstance(publicKey.getAlgorithm());
    boolean b = so.verify(publicKey, sig);
    o = (MyClass) so.getObject();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    keyGen.initialize(1024);// w  ww .ja va  2  s  .  co  m
    KeyPair keypair = keyGen.genKeyPair();
    DSAPrivateKey privateKey = (DSAPrivateKey) keypair.getPrivate();
    DSAPublicKey publicKey = (DSAPublicKey) keypair.getPublic();

    DSAParams dsaParams = privateKey.getParams();
    BigInteger p = dsaParams.getP();
    BigInteger q = dsaParams.getQ();
    BigInteger g = dsaParams.getG();
    BigInteger x = privateKey.getX();
    BigInteger y = publicKey.getY();

    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    KeySpec publicKeySpec = new DSAPublicKeySpec(y, p, q, g);
    PublicKey publicKey1 = keyFactory.generatePublic(publicKeySpec);
    KeySpec privateKeySpec = new DSAPrivateKeySpec(x, p, q, g);
    PrivateKey privateKey1 = keyFactory.generatePrivate(privateKeySpec);

    byte[] buffer = new byte[1024];

    Signature sig = Signature.getInstance(privateKey1.getAlgorithm());
    sig.initSign(privateKey1);
    sig.update(buffer, 0, buffer.length);

    byte[] signature = sig.sign();

    sig = Signature.getInstance(publicKey1.getAlgorithm());
    sig.initVerify(publicKey1);
    sig.update(buffer, 0, buffer.length);
    sig.verify(signature);

}

From source file:at.gv.egiz.pdfas.lib.util.CertificateUtils.java

public static AlgorithmID[] getAlgorithmIDs(X509Certificate signingCertificate)
        throws NoSuchAlgorithmException {
    PublicKey publicKey = signingCertificate.getPublicKey();
    String algorithm = publicKey.getAlgorithm();
    AlgorithmID[] algorithms = new AlgorithmID[2];
    AlgorithmID signatureAlgorithm;/*w w w . ja v a2 s  . co  m*/
    AlgorithmID digestAlgorithm;

    if ("DSA".equals(algorithm)) {
        signatureAlgorithm = AlgorithmID.dsaWithSHA256;
        digestAlgorithm = AlgorithmID.sha256;
    } else if ("RSA".equals(algorithm)) {
        signatureAlgorithm = AlgorithmID.sha256WithRSAEncryption;
        digestAlgorithm = AlgorithmID.sha256;
    } else if (("EC".equals(algorithm)) || ("ECDSA".equals(algorithm))) {

        int fieldSize = 0;
        if (publicKey instanceof ECPublicKey) {
            ECParameterSpec params = ((ECPublicKey) publicKey).getParams();
            fieldSize = params.getCurve().getField().getFieldSize();
        }

        if (fieldSize >= 512) {
            signatureAlgorithm = AlgorithmID.ecdsa_With_SHA512;
            digestAlgorithm = AlgorithmID.sha512;
        } else if (fieldSize >= 256) {
            signatureAlgorithm = AlgorithmID.ecdsa_With_SHA256;
            digestAlgorithm = AlgorithmID.sha256;
        } else {
            signatureAlgorithm = AlgorithmID.ecdsa_With_SHA1;
            digestAlgorithm = AlgorithmID.sha1;
        }
    } else {
        throw new NoSuchAlgorithmException("Public key algorithm '" + algorithm + "' not supported.");
    }

    algorithms[0] = signatureAlgorithm;
    algorithms[1] = digestAlgorithm;

    return algorithms;
}

From source file:hh.learnj.test.license.test.rsa.RSATest.java

/**
 * /*  ww  w.  j  a  v a2  s  .  c o m*/
 * 
 * @param target
 * @throws Exception
 */
static void decryptionByPublicKey(String target) throws Exception {
    PublicKey publicKey = getPublicKey();
    Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicKey);
    cipher.update(decodeBase64(target));
    String source = new String(cipher.doFinal(), "UTF-8");
    System.out.println("??\r\n" + source);
}

From source file:hh.learnj.test.license.test.rsa.RSATest.java

/**
 * // w  w w.  j  a v a 2 s .  com
 * 
 * @param data
 * @return
 * @throws Exception
 */
static String encryptionByPublicKey(String source) throws Exception {
    PublicKey publicKey = getPublicKey();
    Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    cipher.update(source.getBytes("UTF-8"));
    String target = encodeBase64(cipher.doFinal());
    System.out.println("??\r\n" + target);
    return target;
}

From source file:ee.ria.xroad.common.util.CryptoUtils.java

/**
 * Creates a new content verifier using default algorithm.
 * @param key the private key//from  w w w. j a  va2s.  c om
 * @return a new content verifier
 * @throws OperatorCreationException if the content signer cannot be created
 */
public static ContentVerifierProvider createDefaultContentVerifier(PublicKey key)
        throws OperatorCreationException {
    if ("RSA" == key.getAlgorithm()) {
        // SunRsaSign supports only RSA signatures but it is (for some reason) about 2x faster
        // than the BC implementation
        return SUN_VERIFICATION_BUILDER.build(key);
    } else {
        return BC_VERIFICATION_BUILDER.build(key);
    }
}

From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java

/**
* Method used to create an enveloped digital signature for an element of a TAXII document.
*
* @param element the element to be signed
* @param keyEntry the PrivateKeyEntry/*  ww w. ja  v  a  2  s  .c o m*/
* @param cbIndex the index of the Content_Block if we're signing a Content_Block, otherwise set to -1 if we're signing the root element
* @return the status of the operation
*
* Usage Example:
*   String pks = config.getProperty("pathToPublisherKeyStore");
*    String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword"));
*    String keyName = config.getProperty("publisherKeyName");
*    String keyPW = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword"));
*   PrivateKeyEntry keyEntry =  FLAREclientUtil.getKeyEntry(pks, pksPw, keyName, keyPW);
*   List<Integer> statusList = Xmldsig.sign(rootElement, keyEntry, -1);
*/
private static boolean sign(Element element, PrivateKeyEntry keyEntry, int cbIndex) {
    element.normalize();
    boolean status = false;

    //Create XML Signature Factory
    XMLSignatureFactory xmlSigFactory = XMLSignatureFactory.getInstance("DOM");
    PublicKey publicKey = ClientUtil.getPublicKey(keyEntry);
    PrivateKey privateKey = keyEntry.getPrivateKey();
    DOMSignContext dsc = new DOMSignContext(privateKey, element);
    dsc.setDefaultNamespacePrefix("ds");
    dsc.setURIDereferencer(new MyURIDereferencer(element));
    SignedInfo si = null;
    DigestMethod dm = null;
    SignatureMethod sm = null;
    KeyInfo ki = null;
    X509Data xd;
    List<Serializable> x509Content = new ArrayList<>();
    try {
        String algorithm = publicKey.getAlgorithm();
        X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
        x509Content.add(cert.getSubjectX500Principal().getName());
        x509Content.add(cert);
        String algorithmName = cert.getSigAlgName();
        if (algorithm.toUpperCase().contains("RSA")) {
            if (algorithmName.toUpperCase().contains("SHA1")) {
                dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA1, null);
                sm = xmlSigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
            } else if (algorithmName.toUpperCase().contains("SHA2")) {
                dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA256, null);
                sm = xmlSigFactory.newSignatureMethod(RSA_SHA256_URI, null);
            } else {
                logger.error("Error in digital signature application. " + algorithmName + " is not supported.");
            }
            CanonicalizationMethod cm;
            if (cbIndex != -1) {
                cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null);
                String refUri = "#xpointer(//*[local-name()='Content_Block'][" + cbIndex
                        + "]/*[local-name()='Content'][1]/*)";
                List<Reference> references = Collections.singletonList(xmlSigFactory.newReference(refUri, dm));
                si = xmlSigFactory.newSignedInfo(cm, sm, references);
            } else {
                List<Transform> transforms = new ArrayList<>(2);
                transforms.add(xmlSigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
                transforms.add(xmlSigFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
                        (TransformParameterSpec) null));
                cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                        (C14NMethodParameterSpec) null);
                String refUri = "#xpointer(/*)";
                List<Reference> references = Collections
                        .singletonList(xmlSigFactory.newReference(refUri, dm, transforms, null, null));
                si = xmlSigFactory.newSignedInfo(cm, sm, references);
            }
            KeyInfoFactory kif = xmlSigFactory.getKeyInfoFactory();
            xd = kif.newX509Data(x509Content);
            ki = kif.newKeyInfo(Collections.singletonList(xd));
        } else {
            logger.error("Error in digital signature application. " + algorithmName + " is not supported.");
        }
    } catch (NoSuchAlgorithmException ex) {
        logger.error("NoSuchAlgorithm Exception when attempting to digitally sign a document.");
    } catch (InvalidAlgorithmParameterException ex) {
        logger.error("InvalidAlgorithmParameter Exception when attempting to digitally sign a document.");
    }

    // Create a new XML Signature
    XMLSignature signature = xmlSigFactory.newXMLSignature(si, ki);
    try {
        // Sign the document
        signature.sign(dsc);
        status = true;
    } catch (MarshalException ex) {
        logger.error("MarshalException when attempting to digitally sign a document.");
    } catch (XMLSignatureException ex) {
        logger.error("XMLSignature Exception when attempting to digitally sign a document.");
    } catch (Exception e) {
        logger.error("General exception when attempting to digitally sign a document.");
    }
    return status;
}

From source file:cl.nic.dte.util.XMLUtil.java

/**
 * Obtiene el certificado digital contenido en un nodo XML Sinature (<a
 * href="http://www.w3.org/TR/xmldsig-core/">http://www.w3.org/TR/xmldsig-core/</a>)
 * //from   w  w  w.  jav a 2s .  c o  m
 * @param signature
 *            el nodo con el tag &lt;Signature&gt;.
 * @return El certificado digital contenido en el &lt;KeyInfo&gt; o
 *         <code>null</code> en caso que el &lt;Signature&gt; no contenga
 *         tal informaci&oacute;n.
 */
@SuppressWarnings("unchecked")
public static X509Certificate getCertificate(XMLSignature signature) {

    String alg = signature.getSignedInfo().getSignatureMethod().getAlgorithm();
    KeyInfo kinf = signature.getKeyInfo();

    // Check for keyinfo
    if (kinf == null) {
        return null;
    }

    PublicKey pKey = null;
    List<X509Certificate> x509 = new ArrayList<X509Certificate>();

    // I look for the public key and the certificates
    for (XMLStructure xst : (List<XMLStructure>) kinf.getContent()) {
        if (xst instanceof KeyValue) {
            PublicKey pk;
            try {
                pk = ((KeyValue) xst).getPublicKey();
                if (algEquals(alg, pk.getAlgorithm()))
                    pKey = pk;
            } catch (KeyException e) {
                // nothing
            }
        }
        if (xst instanceof X509Data) {
            for (Object cont : ((X509Data) xst).getContent())
                if (cont instanceof X509Certificate)
                    x509.add((X509Certificate) cont);
        }
    }

    // return of the certificates that matchs the public key.
    for (X509Certificate cert : x509) {
        if (cert.getPublicKey().equals(pKey)) {
            return cert;
        }
    }

    return null;
}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateParser.java

private void validatePublicKey() {
    PublicKey publicKey = certificate.getPublicKey();
    result.rejectIfFalse("RSA".equals(publicKey.getAlgorithm()) && publicKey instanceof RSAPublicKey,
            PUBLIC_KEY_CERT_ALGORITHM, publicKey.getAlgorithm());
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        result.warnIfFalse(2048 == rsaPublicKey.getModulus().bitLength(), PUBLIC_KEY_CERT_SIZE,
                String.valueOf(rsaPublicKey.getModulus().bitLength()));
    }// ww  w . j a va  2s.com
}