Java Code Examples for java.security.KeyPairGenerator#initialize()

The following examples show how to use java.security.KeyPairGenerator#initialize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DigitalSignatures.java    From org.hl7.fhir.core with Apache License 2.0 7 votes vote down vote up
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);
}
 
Example 2
Source File: SpecTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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.");
        }
    }
 
Example 3
Source File: GenerateKeypair.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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");
        }
    }
 
Example 4
Source File: Cryptography.java    From zap-android with MIT License 6 votes vote down vote up
@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();
}
 
Example 5
Source File: KeyGenHelper.java    From privacy-friendly-food-tracker with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 6
Source File: GenerateKeypair.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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");
        }
    }
 
Example 7
Source File: GenerateRSAKeyPair.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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");
        }
    }
 
Example 8
Source File: GenerateRSAKeyPair.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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");
        }
    }
 
Example 9
Source File: EncryptionManagerAPI18.java    From samples-android with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 10
Source File: CertificateUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
   }
}
 
Example 11
Source File: EcKeyGeneration.java    From protect with MIT License 5 votes vote down vote up
/**
 * 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);
	}

}
 
Example 12
Source File: CertificateUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
   }
}
 
Example 13
Source File: SecretUtil.java    From DataLink with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化密钥 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;
}
 
Example 14
Source File: LoginEncryptionUtils.java    From Geyser with MIT License 5 votes vote down vote up
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);
}
 
Example 15
Source File: JsonWebKey.java    From swim with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 16
Source File: VerifyRangeCheckOverflow.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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
    }
}
 
Example 17
Source File: CryptUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 18
Source File: Copy.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
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");
}
 
Example 19
Source File: JWKConfiguration.java    From authmore-framework with Apache License 2.0 4 votes vote down vote up
@Bean
public KeyPair keyPair() throws NoSuchAlgorithmException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    return gen.generateKeyPair();
}
 
Example 20
Source File: HDDSKeyGenerator.java    From hadoop-ozone with Apache License 2.0 3 votes vote down vote up
/**
 * 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();
}