Search in sources :

Example 81 with KeyPairGenerator

use of java.security.KeyPairGenerator in project yyl_example by Relucent.

the class Rsa method main.

public static void main(String[] args) throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    // 密钥位数
    keyPairGen.initialize(1024);
    // 密钥对
    KeyPair keyPair = keyPairGen.generateKeyPair();
    // 公钥
    PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    // 私钥
    PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    String publicKeyString = getKeyString(publicKey);
    System.out.println("public:\n" + publicKeyString);
    String privateKeyString = getKeyString(privateKey);
    System.out.println("private:\n" + privateKeyString);
    // 加解密类
    // Cipher.getInstance("RSA/ECB/PKCS1Padding");
    Cipher cipher = Cipher.getInstance("RSA");
    // 明文
    byte[] plainText = "我们都很好!邮件:@sina.com".getBytes();
    // 加密
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] enBytes = cipher.doFinal(plainText);
    // 通过密钥字符串得到密钥
    publicKey = getPublicKey(publicKeyString);
    privateKey = getPrivateKey(privateKeyString);
    // 解密
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] deBytes = cipher.doFinal(enBytes);
    publicKeyString = getKeyString(publicKey);
    System.out.println("public:\n" + publicKeyString);
    privateKeyString = getKeyString(privateKey);
    System.out.println("private:\n" + privateKeyString);
    String s = new String(deBytes);
    System.out.println(s);
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) KeyPairGenerator(java.security.KeyPairGenerator) Cipher(javax.crypto.Cipher) RSAPrivateKey(java.security.interfaces.RSAPrivateKey)

Example 82 with KeyPairGenerator

use of java.security.KeyPairGenerator in project chassis by Kixeye.

the class JettyConnectorRegistry method registerHttpsConnector.

/**
     * Register to listen to HTTPS.
     * 
     * @param server
     * @param address
     * @throws Exception 
     */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned, boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword, String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword, String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();
    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, passwordChars);
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());
        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars, new java.security.cert.Certificate[] { privateKeyCertificate });
        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);
        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;
        sslContextFactory.setTrustAll(true);
    }
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath).getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);
    // SSL Connector
    ServerConnector connector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()), new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.addConnector(connector);
}
Also used : KeyPair(java.security.KeyPair) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) X509Principal(org.bouncycastle.jce.X509Principal) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader)

Example 83 with KeyPairGenerator

use of java.security.KeyPairGenerator in project Gradle-demo by Arisono.

the class DHUtil method initKey.

/**
	 * 甲方初始化并返回密钥对
	 */
public static Map<String, Object> initKey() throws Exception {
    //实例化密钥对生成器
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DH");
    //初始化密钥对生成器  默认是1024  512-1024 & 64的倍数
    keyPairGenerator.initialize(1024);
    //生成密钥对
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    //得到甲方公钥
    DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();
    //得到甲方私钥
    DHPrivateKey peivateKey = (DHPrivateKey) keyPair.getPrivate();
    //将公钥和私钥封装到Map中,方便之后使用
    Map<String, Object> keyMap = new HashMap<String, Object>();
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, peivateKey);
    return keyMap;
}
Also used : DHPrivateKey(javax.crypto.interfaces.DHPrivateKey) KeyPair(java.security.KeyPair) DHPublicKey(javax.crypto.interfaces.DHPublicKey) HashMap(java.util.HashMap) KeyPairGenerator(java.security.KeyPairGenerator)

Example 84 with KeyPairGenerator

use of java.security.KeyPairGenerator in project Gradle-demo by Arisono.

the class RSAUtils method generateKeyBytes.

/**
	 * 生成密钥对。注意这里是生成密钥对KeyPair,再由密钥对获取公私钥
	 * 生成RSA的公钥和私钥
	 * @return
	 */
public static Map<String, byte[]> generateKeyBytes() {
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, byte[]> keyMap = new HashMap<String, byte[]>();
        keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
        keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
        return keyMap;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) HashMap(java.util.HashMap) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey)

Example 85 with KeyPairGenerator

use of java.security.KeyPairGenerator in project geode by apache.

the class HandShake method initDHKeys.

/**
   * Initialize the Diffie-Hellman keys. This method is not thread safe
   */
public static void initDHKeys(DistributionConfig config) throws Exception {
    dhSKAlgo = config.getSecurityClientDHAlgo();
    dhPrivateKey = null;
    dhPublicKey = null;
    // that has authenticator defined.
    if ((dhSKAlgo != null && dhSKAlgo.length() > 0) || securityService.isClientSecurityRequired()) {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
        DHParameterSpec dhSpec = new DHParameterSpec(dhP, dhG, dhL);
        keyGen.initialize(dhSpec);
        KeyPair keypair = keyGen.generateKeyPair();
        // Get the generated public and private keys
        dhPrivateKey = keypair.getPrivate();
        dhPublicKey = keypair.getPublic();
        random = new SecureRandom();
        // Force the random generator to seed itself.
        byte[] someBytes = new byte[48];
        random.nextBytes(someBytes);
    }
}
Also used : KeyPair(java.security.KeyPair) SecureRandom(java.security.SecureRandom) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator)

Aggregations

KeyPairGenerator (java.security.KeyPairGenerator)197 KeyPair (java.security.KeyPair)145 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)43 SecureRandom (java.security.SecureRandom)39 PublicKey (java.security.PublicKey)27 PrivateKey (java.security.PrivateKey)26 X509Certificate (java.security.cert.X509Certificate)23 KeyFactory (java.security.KeyFactory)21 IOException (java.io.IOException)19 BigInteger (java.math.BigInteger)17 GeneralSecurityException (java.security.GeneralSecurityException)15 Signature (java.security.Signature)15 Date (java.util.Date)15 Cipher (javax.crypto.Cipher)15 KeyAgreement (javax.crypto.KeyAgreement)15 RSAPublicKey (java.security.interfaces.RSAPublicKey)14 X500Principal (javax.security.auth.x500.X500Principal)13 ECPrivateKey (java.security.interfaces.ECPrivateKey)12 ECPublicKey (java.security.interfaces.ECPublicKey)12 HashMap (java.util.HashMap)11