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.vmware.demo.SamlUtils.java

/**
 * Generate a public x509 cert, based on a key.
 *
 * @param key KeyPair used to generate public Cert, private key in KeyPair not exposed.
 * @param issuer If generating an SSL Cert, issuer needs to match hostname
 * @return//from   w  w  w .j av  a 2s. co m
 * @throws SamlException
 */
public static X509Certificate generateCert(KeyPair key, String issuer) throws SamlException {
    X509Certificate binCert;
    try {
        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        // create the certificate - version 3
        v3CertGen.reset();
        v3CertGen.setSerialNumber(BigInteger.valueOf(1));
        v3CertGen.setIssuerDN(new X509Principal(issuer));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); //10 years
        v3CertGen.setSubjectDN(new X509Principal(issuer));
        v3CertGen.setPublicKey(key.getPublic());
        v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

        // add the extensions
        v3CertGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.BasicConstraints, false,
                new BasicConstraints(true));

        // generate the actual cert
        binCert = v3CertGen.generate(key.getPrivate());

        // check the cert
        binCert.checkValidity(new Date());
        binCert.verify(key.getPublic());
    } catch (Exception e) {
        throw new SamlException("Failed to generate certificate.", e);
    }

    return binCert;
}

From source file:info.fcrp.keepitsafe.bean.CryptBeanTest.java

@Test
public void assymetric() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();
    PrivateKey priKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();

    Cipher c = Cipher.getInstance("RSA");
    String plain = "plain";
    byte[] plainBytes = plain.getBytes();

    c.init(Cipher.ENCRYPT_MODE, pubKey);
    c.update(plainBytes);//from w w w .j  ava 2  s . c o  m

    byte[] encBytes = c.doFinal();
    String enc = Base64.encodeBase64String(encBytes);
    assertNotSame(plain, enc);

    c.init(Cipher.DECRYPT_MODE, priKey);
    c.update(encBytes);
    byte[] decBytes = c.doFinal();
    String dec = new String(decBytes);

    assertEquals(plain, dec);
}

From source file:org.apache.usergrid.rest.management.ExternalSSOEnabledIT.java

private void generateKey() {
    KeyPair kp = RsaProvider.generateKeyPair(1024);
    publicKey = kp.getPublic();
    privateKey = kp.getPrivate();
}

From source file:org.openengsb.core.util.CipherUtilTest.java

@Before
public void setUp() throws Exception {
    KeyPair kp = CipherUtils.generateKeyPair("RSA", 2048);
    generatedPublickey = kp.getPublic();
    generatedPrivatekey = kp.getPrivate();
}

From source file:com.hyeb.back.login.LoginController.java

/**
 * //  w w w .  j  ava 2  s.c o m
 */
@RequestMapping(value = "/login")
public String login(ModelMap model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
    /** "?"??? */
    final String PRIVATE_KEY_ATTRIBUTE_NAME = "privateKey";

    //HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();       
    Setting setting = SettingUtils.get();
    KeyPair keyPair = RSAUtils.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    request.getSession().setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey);

    String modulus = Base64.encodeBase64String(publicKey.getModulus().toByteArray());//N
    String exponent = Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray());//e
    String captchaId = UUID.randomUUID().toString();
    boolean isBackCaptcha = ArrayUtils.contains(setting.getCaptchaTypes(), CaptchaType.adminLogin);
    model.addAttribute("modulus", modulus);
    model.addAttribute("exponent", exponent);
    model.addAttribute("captchaId", captchaId);
    model.addAttribute("isBackCaptcha", isBackCaptcha);
    String messageStr = null;
    String loginFailure = (String) request
            .getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
    if (loginFailure != null) {
        if (loginFailure.equals("org.apache.shiro.authc.pam.UnsupportedTokenException")) {//??
            messageStr = "admin.captcha.invalid";
        } else if (loginFailure.equals("org.apache.shiro.authc.UnknownAccountException")) {//
            messageStr = "admin.login.unknownAccount";
        } else if (loginFailure.equals("org.apache.shiro.authc.DisabledAccountException")) {//?
            messageStr = "admin.login.disabledAccount";//
        } else if (loginFailure.equals("org.apache.shiro.authc.LockedAccountException")) {//?
            messageStr = "admin.login.lockedAccount";
        } else if (loginFailure.equals("org.apache.shiro.authc.IncorrectCredentialsException")) {//??

            if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.admin)) {
                messageStr = "admin.login.accountLockCount";//?{0}???
            } else {
                messageStr = "admin.login.incorrectCredentials";//???
            }
        } else if (loginFailure.equals("org.apache.shiro.authc.AuthenticationException")) {//
            messageStr = "admin.login.authentication";//??
        }
        if (messageStr != null) {
            Message message = Message.warn(messageStr);
            addFlashMessage(redirectAttributes, message);
        }
    }
    Subject subject = SecurityUtils.getSubject();
    if (subject.isAuthenticated()) {
        return "redirect:/back/main/main";
    } else {
        return "/back/login/login";
    }

}

From source file:org.lightjason.agentspeak.action.buildin.crypto.EAlgorithm.java

/**
 * generates a key/*w  ww.j  a  v  a 2s.com*/
 *
 * @return key pair object (public key / private key or null)
 *
 * @throws NoSuchAlgorithmException on algorithm error
 */
public final Pair<Key, Key> generateKey() throws NoSuchAlgorithmException {
    switch (this) {
    case AES:
    case DES:
        return new ImmutablePair<>(KeyGenerator.getInstance(m_key).generateKey(), null);

    case RSA:
        final KeyPair l_key = KeyPairGenerator.getInstance(m_key).generateKeyPair();
        return new ImmutablePair<>(l_key.getPublic(), l_key.getPrivate());

    default:
        throw new CIllegalStateException(CCommon.languagestring(this, "unknown", this));
    }
}

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

private RSASignature create1() throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);//w  w w  .  j a  v a  2 s.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:cherry.goods.crypto.RSACryptoTest.java

private RSACrypto create1() throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);/*from   ww w . j a v a2s  . com*/
    KeyPair key = keygen.generateKeyPair();
    RSACrypto impl = new RSACrypto();
    impl.setAlgorithm("RSA/ECB/PKCS1Padding");
    impl.setPublicKeyBytes(key.getPublic().getEncoded());
    impl.setPrivateKeyBytes(key.getPrivate().getEncoded());
    return impl;
}

From source file:org.lightjason.agentspeak.action.builtin.crypto.EAlgorithm.java

/**
 * generates a key/* w ww .j  a v a 2 s .  co  m*/
 *
 * @return key pair object (public key / private key or null)
 *
 * @throws NoSuchAlgorithmException on algorithm error
 */
@Nonnull
public final Pair<Key, Key> generateKey() throws NoSuchAlgorithmException {
    switch (this) {
    case AES:
    case DES:
        return new ImmutablePair<>(KeyGenerator.getInstance(m_key).generateKey(), null);

    case RSA:
        final KeyPair l_key = KeyPairGenerator.getInstance(m_key).generateKeyPair();
        return new ImmutablePair<>(l_key.getPublic(), l_key.getPrivate());

    default:
        throw new CIllegalStateException(CCommon.languagestring(this, "unknown", this));
    }
}

From source file:cherry.foundation.crypto.RSASignatureSupportTest.java

private RSASignatureSupport createCrypto() throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);/*  w w w .  ja  v a 2  s  .  c o m*/
    KeyPair key = keygen.generateKeyPair();
    RSASignatureSupport crypto = new RSASignatureSupport();
    crypto.setAlgorithm("SHA256withRSA");
    crypto.setPublicKeyResource(new InMemoryResource(key.getPublic().getEncoded()));
    crypto.setPrivateKeyResource(new InMemoryResource(key.getPrivate().getEncoded()));
    crypto.afterPropertiesSet();
    return crypto;
}