Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

In this page you can find the example usage for java.security KeyPair getPublic.

Prototype

public PublicKey getPublic() 

Source Link

Document

Returns a reference to the public key component of this key pair.

Usage

From source file:com.titilink.common.app.EncryptDecryptUtil.java

public void testRSA() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, SignatureException {
    ///*from w  w  w  .j  a va  2  s  .com*/
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    //?
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    //??
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, privateKey, new SecureRandom());
    byte[] cipherData = cipher
            .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8")));

    //
    Cipher cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, publicKey, new SecureRandom());
    byte[] plainData = cipher1.doFinal(cipherData);
    System.out.println(new String(plainData, Charset.forName("UTF-8")));

    //???????
    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initSign(privateKey);
    signature.update(cipherData);
    byte[] signData = signature.sign();

    //?????
    Signature signature1 = Signature.getInstance("MD5withRSA");
    signature1.initVerify(publicKey);
    signature1.update(cipherData);
    System.out.println(signature1.verify(signData));

}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Verify a RSA key pair with a simple encrypt/decrypt test.
 * /*  w  w w  . jav a  2s . c  o  m*/
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
private static void verifyRSAKeyPair(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    // Validate algorithm is RSA
    Assert.assertTrue(keyPair.getPublic().getAlgorithm().equals(ALGO_RSA));
    Assert.assertTrue(keyPair.getPrivate().getAlgorithm().equals(ALGO_RSA));

    // Generate an array of 10 random bytes
    byte[] plainData = new byte[10];
    Random random = new Random();
    random.nextBytes(plainData);

    // Encrypt using the public key
    Cipher encryptCipher = Cipher.getInstance(ALGO_RSA);
    encryptCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
    byte[] encryptedData = encryptCipher.doFinal(plainData);

    // Decrypt using the private key
    Cipher decryptCipher = Cipher.getInstance(ALGO_RSA);
    decryptCipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
    byte[] decryptedData = decryptCipher.doFinal(encryptedData);

    // Validate plainData is equal to decryptedData
    Assert.assertArrayEquals(plainData, decryptedData);
}

From source file:cherry.goods.crypto.VersionedSignatureTest.java

private RSASignature createRSASignature() throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);//  w  w  w.  j a va 2s  .c  om
    KeyPair key = keygen.generateKeyPair();
    RSASignature impl = new RSASignature();
    impl.setAlgorithm("SHA256withRSA");
    impl.setPublicKeyBytes(key.getPublic().getEncoded());
    impl.setPrivateKeyBytes(key.getPrivate().getEncoded());
    return impl;
}

From source file:com.kuzumeji.platform.standard.SecurityServiceTest.java

@Test
public void testEncryptDecrypt() {
    // RSA???/*from w  w w  .ja  va  2  s .c  o m*/
    final KeyPair keyPair = testee.generateKeyPair();
    final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    // ???
    final char[] password = "hello, world!!".toCharArray();
    final byte[] salt = new byte[] { 1 };
    final byte[] secretKey = testee.createCommonKey(password, salt);
    LOG.debug("? : {}", Hex.encodeHexString(secretKey));
    // ???
    final byte[] encryptedSecretKey = testee.encrypt(publicKey, secretKey);
    LOG.debug("??? : {}", Hex.encodeHexString(encryptedSecretKey));
    // ???
    final byte[] decryptedSecretKey = testee.decrypt(privateKey, encryptedSecretKey);
    assertThat(decryptedSecretKey, is(secretKey));
    LOG.debug("??? : {}", Hex.encodeHexString(decryptedSecretKey));
    // ???
    final String text = "?????????????";
    LOG.debug(" : {}", text);
    final SecuredData context = testee.encrypt(secretKey, text.getBytes());
    LOG.debug("??={}", Hex.encodeHexString(context.getEncrypted()));
    LOG.debug("???(IV)={}", Hex.encodeHexString(context.getVector()));
    // ???
    final byte[] decryptedMessage = testee.decrypt(secretKey, context);
    assertThat(decryptedMessage, is(text.getBytes()));
    LOG.debug("? : {}", new String(decryptedMessage));
}

From source file:org.apache.xml.security.test.signature.XmlSecTest.java

private void checkXmlSignatureSoftwareStack(boolean cert) throws Exception {
    Init.init();/*from w  w w . j  a va2  s . c om*/
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document testDocument = documentBuilder.newDocument();

    Element rootElement = testDocument.createElementNS("urn:namespace", "tns:document");
    rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:namespace");
    testDocument.appendChild(rootElement);
    Element childElement = testDocument.createElementNS("urn:childnamespace", "t:child");
    childElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:t", "urn:childnamespace");
    childElement.appendChild(testDocument.createTextNode("hello world"));
    rootElement.appendChild(childElement);

    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    X509Certificate signingCert = null;
    if (cert) {
        // get key & self-signed certificate from keystore
        String fs = System.getProperty("file.separator");
        FileInputStream fis = new FileInputStream(BASEDIR + fs + "data" + fs + "test.jks");
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(fis, "changeit".toCharArray());
        signingCert = (X509Certificate) ks.getCertificate("mullan");
        publicKey = signingCert.getPublicKey();
        privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray());
    } else {
        KeyPair keyPair = KeyPairGenerator.getInstance("DSA").generateKeyPair();
        publicKey = keyPair.getPublic();
        privateKey = keyPair.getPrivate();
    }

    XMLSignature signature = new XMLSignature(testDocument, "", XMLSignature.ALGO_ID_SIGNATURE_DSA,
            Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);

    Element signatureElement = signature.getElement();
    rootElement.appendChild(signatureElement);

    Transforms transforms = new Transforms(testDocument);
    XPathContainer xpath = new XPathContainer(testDocument);
    xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
    xpath.setXPath("not(ancestor-or-self::ds:Signature)");
    transforms.addTransform(Transforms.TRANSFORM_XPATH, xpath.getElementPlusReturns());
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    signature.addDocument("", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1);

    if (cert) {
        signature.addKeyInfo(signingCert);
    } else {
        signature.addKeyInfo(publicKey);
    }

    Element nsElement = testDocument.createElementNS(null, "nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);

    signature.sign(privateKey);

    // TransformerFactory tf = TransformerFactory.newInstance();
    // Transformer t = tf.newTransformer();
    // t.transform(new DOMSource(testDocument), new StreamResult(System.out));

    NodeList signatureElems = XPathAPI.selectNodeList(testDocument, "//ds:Signature", nsElement);
    signatureElement = (Element) signatureElems.item(0);
    XMLSignature signatureToVerify = new XMLSignature(signatureElement, "");

    boolean signResult = signatureToVerify.checkSignatureValue(publicKey);

    assertTrue(signResult);
}

From source file:org.panbox.desktop.devicemgmt.TestAddDevice.java

@Test
public void test() {
    try {// www  . java 2 s .co m
        int before = manager.getDeviceList().size();

        KeyPair devKeyPair = CryptCore.generateKeypair();
        X509Certificate deviceCert = CryptCore.createSelfSignedX509Certificate(devKeyPair.getPrivate(),
                devKeyPair.getPublic(), new PairingIPersonDummy("email", "firstname", "lastname"));

        manager.addDevice("testdeviceDesktop", deviceCert, DeviceType.DESKTOP);

        assertEquals(before + 1, manager.getDeviceList().size());

        devKeyPair = CryptCore.generateKeypair();
        deviceCert = CryptCore.createSelfSignedX509Certificate(devKeyPair.getPrivate(), devKeyPair.getPublic(),
                new PairingIPersonDummy("email", "firstname", "lastname"));

        manager.addDevice("testdeviceMobile", deviceCert, DeviceType.MOBILE);

        assertEquals(before + 2, manager.getDeviceList().size());
    } catch (DeviceManagerException e) {
        e.printStackTrace();
        fail();
    }
}

From source file:org.signserver.module.xades.signer.XAdESSignerUnitTest.java

private static MockedCryptoToken generateTokenWithIntermediateCert() throws Exception {
    final JcaX509CertificateConverter conv = new JcaX509CertificateConverter();
    final KeyPair rootcaKeyPair = CryptoUtils.generateRSA(1024);
    final X509CertificateHolder rootcaCert = new CertBuilder().setSelfSignKeyPair(rootcaKeyPair)
            .setSubject("CN=Root, O=XAdES Test, C=SE")
            .addExtension(new CertExt(Extension.keyUsage, false,
                    new X509KeyUsage(X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)))
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(true))).build();
    final KeyPair subcaKeyPair = CryptoUtils.generateRSA(1024);
    final X509CertificateHolder subcaCert = new CertBuilder().setIssuerPrivateKey(rootcaKeyPair.getPrivate())
            .setIssuer(rootcaCert.getSubject()).setSubjectPublicKey(subcaKeyPair.getPublic())
            .setSubject("CN=Sub, O=XAdES Test, C=SE")
            .addExtension(new CertExt(Extension.keyUsage, false,
                    new X509KeyUsage(X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)))
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(true))).build();

    final KeyPair signerKeyPair = CryptoUtils.generateRSA(1024);
    final X509CertificateHolder signerCert = new CertBuilder().setIssuerPrivateKey(subcaKeyPair.getPrivate())
            .setIssuer(subcaCert.getSubject()).setSubjectPublicKey(signerKeyPair.getPublic())
            .setSubject("CN=Signer 1, O=XAdES Test, C=SE")
            .addExtension(new CertExt(Extension.basicConstraints, false, new BasicConstraints(false))).build();

    final List<Certificate> chain = Arrays.<Certificate>asList(conv.getCertificate(signerCert),
            conv.getCertificate(subcaCert), conv.getCertificate(rootcaCert));

    return new MockedCryptoToken(signerKeyPair.getPrivate(), signerKeyPair.getPublic(),
            conv.getCertificate(signerCert), chain, "BC");
}

From source file:hudson.cli.Connection.java

private String detectKeyAlgorithm(KeyPair kp) {
    return detectKeyAlgorithm(kp.getPublic());
}

From source file:org.openbaton.nfvo.core.api.KeyManagement.java

@Override
public String generateKey(String projectId, String name) throws IOException, NoSuchAlgorithmException {
    log.debug("Generating keypair");
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);//from ww w  . ja  v a 2s.com
    KeyPair keyPair = keyGen.genKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    String publicKeyString = encodePublicKey(publicKey, name);
    Key key = new Key();
    key.setName(name);
    key.setProjectId(projectId);
    key.setFingerprint(calculateFingerprint(publicKey.getEncoded()));
    key.setPublicKey(publicKeyString);
    log.debug(publicKeyString);
    keyRepository.save(key);
    log.info("Added new key: " + key);
    return parsePrivateKey(privateKey.getEncoded());
}

From source file:hudson.plugins.ec2.EC2PrivateKey.java

public String getPublicFingerprint() throws IOException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    Reader r = new BufferedReader(new StringReader(privateKey.toString()));
    PEMReader pem = new PEMReader(r, new PasswordFinder() {
        public char[] getPassword() {
            throw PRIVATE_KEY_WITH_PASSWORD;
        }/*from w  w w . ja  v  a 2 s.c  om*/
    });

    try {
        KeyPair pair = (KeyPair) pem.readObject();
        if (pair == null)
            return null;
        PublicKey key = pair.getPublic();
        return digestOpt(key, "MD5");
    } catch (RuntimeException e) {
        if (e == PRIVATE_KEY_WITH_PASSWORD)
            throw new IOException("This private key is password protected, which isn't supported yet");
        throw e;
    }
}