java.security.KeyPairGenerator#initialize ( )源码实例Demo

下面列出了java.security.KeyPairGenerator#initialize ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: dragonwell8_jdk   文件: GenerateKeypair.java
public static void main(String[] args) throws Exception {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(512);

        // test generateKeyPair
        KeyPair kpair = kpg.generateKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }

        // test genKeyPair
        kpair = kpg.genKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }
    }
 
源代码2 项目: TencentKona-8   文件: SpecTest.java
public static void main(String[] args) throws Exception {

        int size = 0;

        if (args.length >= 1) {
            size = Integer.parseInt(args[0]);
        } else {
            throw new RuntimeException("Missing keysize to test with");
        }

        BigInteger publicExponent
                = (args.length >= 2) ? new BigInteger(args[1]) : RSAKeyGenParameterSpec.F4;

        System.out.println("Running test with key size: " + size
                + " and public exponent: " + publicExponent);

        KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(KEYALG, PROVIDER);
        kpg1.initialize(new RSAKeyGenParameterSpec(size, publicExponent));
        if (!specTest(kpg1.generateKeyPair(), publicExponent)) {
            throw new RuntimeException("Test failed.");
        }
    }
 
源代码3 项目: openjdk-jdk8u   文件: GenerateKeypair.java
public static void main(String[] args) throws Exception {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(512);

        // test generateKeyPair
        KeyPair kpair = kpg.generateKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }

        // test genKeyPair
        kpair = kpg.genKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }
    }
 
源代码4 项目: DataLink   文件: SecretUtil.java
/**
 * 初始化密钥 for RSA ALGORITHM
 *
 * @return
 * @throws Exception
 */
public static String[] initKey() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator
            .getInstance(KEY_ALGORITHM_RSA);
    keyPairGen.initialize(1024);

    KeyPair keyPair = keyPairGen.generateKeyPair();

    // 公钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

    // 私钥
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

    String[] publicAndPrivateKey = {
            encryptBASE64(publicKey.getEncoded()),
            encryptBASE64(privateKey.getEncoded())};

    return publicAndPrivateKey;
}
 
/**
 * Generates a rsa key pair if it not exists.
 *
 * @param context the application context
 */
public static void generateKey(Context context) throws Exception {
    KeyStore keyStore;
    keyStore = KeyStore.getInstance(AndroidKeyStore);
    keyStore.load(null, null);

    // Generate the RSA key pairs for encryption
    if (!keyStore.containsAlias(KEY_ALIAS)) {
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 30);

        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(KEY_ALIAS)
                .setSubject(new X500Principal("CN=" + KEY_ALIAS))
                .setSerialNumber(BigInteger.TEN)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, AndroidKeyStore);
        kpg.initialize(spec);
        kpg.generateKeyPair();
    }
}
 
源代码6 项目: zap-android   文件: Cryptography.java
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void generateKeysForAPILessThanM(String keyAlias) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CertificateException, UnrecoverableEntryException, NoSuchPaddingException, KeyStoreException, InvalidKeyException, IOException {
    // Generate a key pair for encryption
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 30);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext)
            .setAlias(keyAlias)
            .setSubject(new X500Principal("CN=" + keyAlias))
            .setSerialNumber(BigInteger.TEN)
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM_NAME, ANDROID_KEY_STORE_NAME);
    kpg.initialize(spec);
    kpg.generateKeyPair();

    saveEncryptedKey();
}
 
源代码7 项目: PowerFileExplorer   文件: CryptUtil.java
/**
 * Generates a RSA public/private key pair to encrypt AES key
 * @param context
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void generateKeyPair(Context context) throws KeyStoreException,
        CertificateException, NoSuchAlgorithmException, IOException, NoSuchProviderException,
        InvalidAlgorithmParameterException {

    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_ANDROID);
    keyStore.load(null);

    if (!keyStore.containsAlias(KEY_ALIAS_AMAZE)) {
        // generate a RSA key pair to encrypt/decrypt AES key from preferences
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 30);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", KEY_STORE_ANDROID);

        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(KEY_ALIAS_AMAZE)
                .setSubject(new X500Principal("CN=" + KEY_ALIAS_AMAZE))
                .setSerialNumber(BigInteger.TEN)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();

        keyPairGenerator.initialize(spec);
        keyPairGenerator.generateKeyPair();
    }
}
 
public static void main(String[] args) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
    keyPairGenerator.initialize(1024);
    KeyPair keys = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keys.getPublic();
    byte[] sigBytes = new byte[100];

    Signature signature = Signature.getInstance("SHA1withDSA");
    signature.initVerify(publicKey);
    try {
        signature.verify(sigBytes, Integer.MAX_VALUE, 1);
    } catch (IllegalArgumentException ex) {
        // Expected
    }
}
 
源代码9 项目: swim   文件: JsonWebKey.java
private static ECParameterSpec createECParameterSpec(String stdName) {
  try {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
    final ECGenParameterSpec parameterSpec = new ECGenParameterSpec(stdName);
    keyPairGenerator.initialize(parameterSpec);
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();
    final ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
    return publicKey.getParams();
  } catch (GeneralSecurityException cause) {
    throw new RuntimeException(cause);
  }
}
 
源代码10 项目: Geyser   文件: LoginEncryptionUtils.java
private static void startEncryptionHandshake(GeyserSession session, PublicKey key) throws Exception {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(new ECGenParameterSpec("secp384r1"));
    KeyPair serverKeyPair = generator.generateKeyPair();

    byte[] token = EncryptionUtils.generateRandomToken();
    SecretKey encryptionKey = EncryptionUtils.getSecretKey(serverKeyPair.getPrivate(), key, token);
    session.getUpstream().getSession().enableEncryption(encryptionKey);

    ServerToClientHandshakePacket packet = new ServerToClientHandshakePacket();
    packet.setJwt(EncryptionUtils.createHandshakeJwt(serverKeyPair, token).serialize());
    session.sendUpstreamPacketImmediately(packet);
}
 
源代码11 项目: jdk8u60   文件: GenerateRSAKeyPair.java
public static void main(String[] args) throws Exception {

        RSAKeyGenParameterSpec rsaSpec =
        new RSAKeyGenParameterSpec (1024, RSAKeyGenParameterSpec.F4);
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
        kpg.initialize(rsaSpec);

        // test generateKeyPair
        KeyPair kpair = kpg.generateKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }
    }
 
源代码12 项目: freehealth-connector   文件: CertificateUtils.java
public static KeyPair generateKeyPair() {
   String authKeyAlgorithm = RaPropertiesLoader.getProperty("authentication.key.algorithm");
   Integer authKeySize = Integer.parseInt(RaPropertiesLoader.getProperty("authentication.key.size", "0"));

   try {
      KeyPairGenerator kg = KeyPairGenerator.getInstance(authKeyAlgorithm);
      kg.initialize(authKeySize.intValue(), new SecureRandom());
      return kg.generateKeyPair();
   } catch (NoSuchAlgorithmException var3) {
      throw new IllegalArgumentException(authKeyAlgorithm + " key algorithm is unknown to the security provider", var3);
   }
}
 
源代码13 项目: protect   文件: EcKeyGeneration.java
/**
 * Generate elliptic curve key pairs
 * 
 * @return
 */
public static final KeyPair generateKeyPair() {

	// Initalize key pair generator
	final KeyPairGenerator keyGen;
	try {
		keyGen = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
		keyGen.initialize(new ECGenParameterSpec(curve.getName()));
		return keyGen.generateKeyPair();
	} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException e) {
		throw new RuntimeException(e);
	}

}
 
源代码14 项目: freehealth-connector   文件: CertificateUtils.java
public static KeyPair generateKeyPair() {
   String authKeyAlgorithm = RaPropertiesLoader.getProperty("authentication.key.algorithm");
   Integer authKeySize = Integer.parseInt(RaPropertiesLoader.getProperty("authentication.key.size", "0"));

   try {
      KeyPairGenerator kg = KeyPairGenerator.getInstance(authKeyAlgorithm);
      kg.initialize(authKeySize, new SecureRandom());
      return kg.generateKeyPair();
   } catch (NoSuchAlgorithmException var3) {
      throw new IllegalArgumentException(authKeyAlgorithm + " key algorithm is unknown to the security provider", var3);
   }
}
 
源代码15 项目: org.hl7.fhir.core   文件: DigitalSignatures.java
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException, org.hl7.fhir.exceptions.FHIRException {
  // http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
  //
  byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
  // load the document that's going to be signed
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  dbf.setNamespaceAware(true);
  DocumentBuilder builder = dbf.newDocumentBuilder();  
  Document doc = builder.parse(new ByteArrayInputStream(inputXml)); 
  
  // create a key pair
  KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  kpg.initialize(512);
  KeyPair kp = kpg.generateKeyPair(); 
  
  // sign the document
  DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); 
  XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 
 
  Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
  SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
  
  KeyInfoFactory kif = fac.getKeyInfoFactory(); 
  KeyValue kv = kif.newKeyValue(kp.getPublic());
  KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
  XMLSignature signature = fac.newXMLSignature(si, ki); 
  signature.sign(dsc);
  
  OutputStream os = System.out;
  new XmlGenerator().generate(doc.getDocumentElement(), os);
}
 
源代码16 项目: samples-android   文件: EncryptionManagerAPI18.java
@Override
boolean generateKeyPair(Context context, KeyPairGenerator generator, String keyAlias,
                        int keySize, String encryptionPadding, String blockMode,
                        boolean isStrongBoxBacked, @Nullable byte[] seed) {
    Calendar startDate = Calendar.getInstance();
    //probable fix for the timezone issue
    startDate.add(Calendar.HOUR_OF_DAY, RSA_CALENDAR_HOURS_OFFSET);
    Calendar endDate = Calendar.getInstance();
    endDate.add(Calendar.YEAR, RSA_CALENDAR_MAX_YEARS);

    try {
        KeyPairGeneratorSpec.Builder builder = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(keyAlias)
                .setSerialNumber(BigInteger.ONE)
                .setSubject(new X500Principal(
                        "CN = Secured Preference Store, O = Devliving Online"))
                .setStartDate(startDate.getTime())
                .setEndDate(endDate.getTime());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            builder.setKeySize(keySize);
        }
        if (seed != null && seed.length > 0) {
            SecureRandom random = new SecureRandom(seed);
            generator.initialize(builder.build(), random);
        } else {
            generator.initialize(builder.build());
        }

        return true;
    } catch (InvalidAlgorithmParameterException e) {
        Log.e(TAG, "initialize KeyPairGenerator: ", e);
    }
    return false;
}
 
源代码17 项目: openjdk-jdk8u   文件: GenerateRSAKeyPair.java
public static void main(String[] args) throws Exception {

        RSAKeyGenParameterSpec rsaSpec =
        new RSAKeyGenParameterSpec (1024, RSAKeyGenParameterSpec.F4);
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
        kpg.initialize(rsaSpec);

        // test generateKeyPair
        KeyPair kpair = kpg.generateKeyPair();
        if (kpair == null) {
            throw new Exception("no keypair generated");
        }
    }
 
源代码18 项目: openjdk-jdk8u   文件: Copy.java
public static void main(String args[]) throws Exception {
    KeyPairGenerator kg = KeyPairGenerator.getInstance(DSA);
    kg.initialize(KEY_SIZE);
    KeyPair kp = kg.genKeyPair();

    Signature signature = Signature.getInstance(DSA);
    Test original = new Test();
    SignedObject so = new SignedObject(original, kp.getPrivate(),
            signature);
    System.out.println("Signature algorithm: " + so.getAlgorithm());

    signature = Signature.getInstance(DSA, "SUN");
    if (!so.verify(kp.getPublic(), signature)) {
        throw new RuntimeException("Verification failed");
    }

    kg = KeyPairGenerator.getInstance(DSA);
    kg.initialize(KEY_SIZE);
    kp = kg.genKeyPair();

    if (so.verify(kp.getPublic(), signature)) {
        throw new RuntimeException("Unexpected success");
    }

    Object copy = so.getObject();
    if (!original.equals(copy)) {
        throw new RuntimeException("Signed object is not equal "
                + "to original one: " + copy);
    }

    /*
     * The signed object is a copy of an original one.
     * Once the copy is made, further manipulation
     * of the original object shouldn't has any effect on the copy.
     */
    original.set(MAGIC - 1);
    copy = so.getObject();
    if (original.equals(copy)) {
        throw new RuntimeException("Signed object is not a copy "
                + "of original one: " + copy);
    }

    System.out.println("Test passed");
}
 
源代码19 项目: authmore-framework   文件: JWKConfiguration.java
@Bean
public KeyPair keyPair() throws NoSuchAlgorithmException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    return gen.generateKeyPair();
}
 
源代码20 项目: hadoop-ozone   文件: HDDSKeyGenerator.java
/**
 * Custom Key Generation, all values are user provided.
 *
 * @param size - Key Size
 * @param algorithm - Algorithm to use
 * @param provider - Security provider.
 * @return KeyPair.
 * @throws NoSuchProviderException  - On Error, due to missing Java
 *                                  dependencies.
 * @throws NoSuchAlgorithmException - On Error,  due to missing Java
 *                                  dependencies.
 */
public KeyPair generateKey(int size, String algorithm, String provider)
    throws NoSuchProviderException, NoSuchAlgorithmException {
  if (LOG.isDebugEnabled()) {
    LOG.debug("Generating key pair using size:{}, Algorithm:{}, Provider:{}",
        size, algorithm, provider);
  }
  KeyPairGenerator generator = KeyPairGenerator
      .getInstance(algorithm, provider);
  generator.initialize(size);
  return generator.generateKeyPair();
}