当前位置: 首页>>代码示例>>Java>>正文


Java KeyPairGenerator.initialize方法代码示例

本文整理汇总了Java中java.security.KeyPairGenerator.initialize方法的典型用法代码示例。如果您正苦于以下问题:Java KeyPairGenerator.initialize方法的具体用法?Java KeyPairGenerator.initialize怎么用?Java KeyPairGenerator.initialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.security.KeyPairGenerator的用法示例。


在下文中一共展示了KeyPairGenerator.initialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: test

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
public static void test() throws Exception {
	KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

    keyGen.initialize(512, new SecureRandom());

    KeyPair keyPair = keyGen.generateKeyPair();
    Signature signature = Signature.getInstance("SHA1withRSA");

    signature.initSign(keyPair.getPrivate());

    byte[] message = "abc".getBytes();
    signature.update(message);

    byte[] sigBytes = signature.sign();
    signature.initVerify(keyPair.getPublic());
    signature.update(message);
    System.out.println(signature.verify(sigBytes));
	
}
 
开发者ID:atul19971,项目名称:crypto4ora,代码行数:20,代码来源:Client.java

示例2: createKeys

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
/**
 * Creates a public and private key and stores it using the AndroidKeyStore,
 * so that only this application will be able to access the keys.
 */
@SuppressWarnings("deprecation")
public void createKeys() throws Exception {
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);
    if (keyStore.containsAlias(alias)) {
        Log.d(TAG, "[containsAlias]");
        return;
    }

    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 30);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
        .setAlias(alias)
        .setSubject(new X500Principal("CN=" + alias))
        .setSerialNumber(BigInteger.TEN)
        .setStartDate(start.getTime())
        .setEndDate(end.getTime())
        .build();
    KeyPairGenerator generator = KeyPairGenerator.getInstance(TYPE_RSA, ANDROID_KEY_STORE);
    generator.initialize(spec);
    KeyPair keyPair = generator.generateKeyPair();
    Log.d(TAG, "Public Key is: " + keyPair.getPublic().toString());
}
 
开发者ID:drakeet,项目名称:rebase-android,代码行数:29,代码来源:BlackBox.java

示例3: checkSignatureForToken

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@Test
public void checkSignatureForToken() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(512);
  KeyPair keys = keyGen.genKeyPair();

  FixedClock clock = new FixedClock(2002L);

  FirebaseTokenFactory tokenFactory = new FirebaseTokenFactory(FACTORY, clock);

  String jwt =
      tokenFactory.createSignedCustomAuthTokenForUser(
          USER_ID, EXTRA_CLAIMS, ISSUER, keys.getPrivate());

  FirebaseCustomAuthToken signedJwt = FirebaseCustomAuthToken.parse(FACTORY, jwt);
  assertEquals("RS256", signedJwt.getHeader().getAlgorithm());
  assertEquals(ISSUER, signedJwt.getPayload().getIssuer());
  assertEquals(ISSUER, signedJwt.getPayload().getSubject());
  assertEquals(USER_ID, signedJwt.getPayload().getUid());
  assertEquals(2L, signedJwt.getPayload().getIssuedAtTimeSeconds().longValue());

  assertTrue(TestUtils.verifySignature(signedJwt, ImmutableList.of(keys.getPublic())));
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:24,代码来源:FirebaseTokenFactoryTest.java

示例4: testKeyPairGeneratorEccMultipleKeyGen

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@Test
public void testKeyPairGeneratorEccMultipleKeyGen()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           InvalidAlgorithmParameterException {

    if (enabledCurves.size() > 0) {

        KeyPairGenerator kpg =
            KeyPairGenerator.getInstance("EC", "wolfJCE");

        ECGenParameterSpec ecSpec =
            new ECGenParameterSpec(enabledCurves.get(0));
        kpg.initialize(ecSpec);

        KeyPair kp1 = kpg.generateKeyPair();
        KeyPair kp2 = kpg.generateKeyPair();
    }
}
 
开发者ID:wolfSSL,项目名称:wolfcrypt-jni,代码行数:19,代码来源:WolfCryptKeyPairGeneratorTest.java

示例5: testKeyPairGeneratorEccKeyGenAllCurves

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@Test
public void testKeyPairGeneratorEccKeyGenAllCurves()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           InvalidAlgorithmParameterException {

    /* try generating keys for all supported curves */
    for (int i = 0; i < enabledCurves.size(); i++) {

        KeyPairGenerator kpg =
            KeyPairGenerator.getInstance("EC", "wolfJCE");

        ECGenParameterSpec ecSpec =
            new ECGenParameterSpec(enabledCurves.get(i));
        kpg.initialize(ecSpec);

        KeyPair kp = kpg.generateKeyPair();
    }
}
 
开发者ID:wolfSSL,项目名称:wolfcrypt-jni,代码行数:19,代码来源:WolfCryptKeyPairGeneratorTest.java

示例6: writeReadTest

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@Test
public void writeReadTest() throws Exception {
  for (ValueSigner signer : ValueSigner.values()) {
    KeyPairGenerator gen = KeyPairGenerator.getInstance(signer.getKeyGenerationAlgorithm());
    if (signer == ValueSigner.ECDSA) {
      gen.initialize(256);
    } else {
      gen.initialize(1024);
    }

    KeyPair pair = gen.generateKeyPair();
    byte[] keyId = String.format("%s_%s", gen.getAlgorithm(), "test").getBytes(ENCODING_CHARSET);
    LocalSignatureKeyContainer container = new LocalSignatureKeyContainer(pair, keyId);

    File file = folder.newFile();
    FileWriter writer = new FileWriter(file);
    container.write(writer);
    writer.close();

    LocalSignatureKeyContainer container2 = LocalSignatureKeyContainer.read(new FileReader(file));
    assertThat("has matching keys", container2.getSigningKey().key.getEncoded(), equalTo(container.getSigningKey().key.getEncoded()));
    assertThat("has matching keys", container2.getSigningKey().id, equalTo(container.getSigningKey().id));
    assertThat("has matching keys", container2.getVerifyingKey(keyId).getEncoded(), equalTo(container.getVerifyingKey(keyId).getEncoded()));
  }

}
 
开发者ID:mit-ll,项目名称:PACE,代码行数:27,代码来源:LocalSignatureKeyContainerTest.java

示例7: generateEphemeralKeys

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
/**
 * Generates a random key pair based on a curve
 * @param curve the curve to use
 * @return a randomly generated KeyPair
 */
public static KeyPair generateEphemeralKeys(EllipticCurveParameters curve) {
    try {
        final ECParameterSpec curveParams = EllipticCurveParameters.encodeECParameterSpec(curve);
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
        keyPairGenerator.initialize(curveParams);

        return keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }

    return null;
}
 
开发者ID:mDL-ILP,项目名称:mDL-ILP,代码行数:19,代码来源:ECCUtils.java

示例8: generateDSAKeypair

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
public static KeyPair generateDSAKeypair(int plength, int qlength, SecureRandom random)
        throws NoSuchAlgorithmException, NoSuchProviderException,
            InvalidAlgorithmParameterException {
    DSAParameterSpec dsaParamSpec = DSAParameterCache.getDSAParameterSpec(plength, qlength,
            random);
    KeyPairGenerator kpGen = getKeyPairGenerator("DSA");
    synchronized (kpGen) {
        kpGen.initialize(dsaParamSpec, random);
        return kpGen.generateKeyPair();
    }
}
 
开发者ID:xipki,项目名称:xitk,代码行数:12,代码来源:KeyUtil.java

示例9: createKeyPair

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@TargetApi(23)
   public KeyPair createKeyPair(String keyName, boolean invalidatedByBiometricEnrollment) throws CryptoException
{
	KeyPair keyPair = null;

	try {
		KeyStore mKeyStore = KeyStore.getInstance(REST_AUTH_KEYSTORE_NAME);
		mKeyStore.load(null);

		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
				KeyProperties.KEY_ALGORITHM_EC, REST_AUTH_KEYSTORE_NAME);


		KeyGenParameterSpec.Builder builder
				= new KeyGenParameterSpec.Builder(keyName,
				                                  KeyProperties.PURPOSE_ENCRYPT |
						                          KeyProperties.PURPOSE_DECRYPT |
						                          KeyProperties.PURPOSE_SIGN)
				.setDigests(KeyProperties.DIGEST_SHA256)
				.setAlgorithmParameterSpec(new ECGenParameterSpec(REST_AUTH_EC_CURVE))
				.setUserAuthenticationRequired(true);

           // This call is only available on API level >= 24.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);
		}

		keyPairGenerator.initialize(builder.build());
		keyPair = keyPairGenerator.generateKeyPair();

	} catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException |
		   InvalidAlgorithmParameterException | CertificateException | IOException e)
	{
		throw new CryptoException(e.getMessage());
	}

	return keyPair;
}
 
开发者ID:thiscitizenis,项目名称:citizen-sdk-android,代码行数:39,代码来源:CryptoService.java

示例10: getRSAKeyPair

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
private static KeyPair getRSAKeyPair() {
	try {
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(2048);
		return keyGen.generateKeyPair();
	} catch (Exception e) {
		System.out.println("Unable to initialize RSA key pair.");
		e.printStackTrace();
		return null;
	}
}
 
开发者ID:gahana,项目名称:edge-jwt-sample,代码行数:12,代码来源:JWTUtil.java

示例11: generateRSAKeyPair

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
/**
 * 随机生成RSA密钥对
 *
 * @param keyLength
 *            密钥长度,范围:512~2048<br>
 *            一般1024
 * @return
 */
public static KeyPair generateRSAKeyPair(int keyLength)
{
    try
    {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
        kpg.initialize(keyLength);
        return kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e)
    {
        e.printStackTrace();
        return null;
    }
}
 
开发者ID:Herbertyy,项目名称:HerbertyyRepository,代码行数:22,代码来源:RSAUtils.java

示例12: AsymmetricKeys

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
public AsymmetricKeys() throws Exception {
    super(asymmetricKeyAlgorithm);
    KeyPairGenerator keygen = KeyPairGenerator.getInstance(asymmetricKeyAlgorithm);
    keygen.initialize(keySize);
    KeyPair pair = keygen.generateKeyPair();
    publicKey = pair.getPublic();
    privateKey = pair.getPrivate();
}
 
开发者ID:Baizey,项目名称:Helpers,代码行数:9,代码来源:AsymmetricKeys.java

示例13: genKeyPair

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
/**
 * <p>
 * 生成密钥对(公钥和私钥)
 * </p>
 *
 * @return
 * @throws Exception
 */
public static Map<String, Object> genKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    Map<String, Object> keyMap = new HashMap<String, Object>(2);
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
}
 
开发者ID:angcyo,项目名称:RLibrary,代码行数:20,代码来源:RSAUtils.java

示例14: generateKey

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
/**
 * Generate key which contains a pair of private and public key using 1024
 * bytes. Store the set of keys in Prvate.key and Public.key files.
 *
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws FileNotFoundException
 */
public static KeyPair generateKey(String publicKeyFilePath, String privateKeyFilePath) {
 try {
  final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
  keyGen.initialize(1024);
  final KeyPair key = keyGen.generateKeyPair();

  File privateKeyFile = new File(privateKeyFilePath);
  File publicKeyFile = new File(publicKeyFilePath);
  
  // Create files to store public and private key
     if (privateKeyFile.getParentFile() != null) {
   	  privateKeyFile.getParentFile().mkdirs();
     }
     privateKeyFile.createNewFile();

     if (publicKeyFile.getParentFile() != null) {
   	  publicKeyFile.getParentFile().mkdirs();
     }
     publicKeyFile.createNewFile();

     // Saving the Public key in a file
     ObjectOutputStream publicKeyOS = new ObjectOutputStream(new FileOutputStream(publicKeyFile));
     publicKeyOS.writeObject(key.getPublic());
     publicKeyOS.close();

     // Saving the Private key in a file
     ObjectOutputStream privateKeyOS = new ObjectOutputStream(new FileOutputStream(privateKeyFile));
     privateKeyOS.writeObject(key.getPrivate());
     privateKeyOS.close();
     
     return key;
 } catch (Exception e) {
  e.printStackTrace();
  
  return null;
 }
}
 
开发者ID:lukasbischof,项目名称:Orsum-occulendi,代码行数:46,代码来源:RSAUtil.java

示例15: main

import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@Override
public void main(Provider p) throws Exception {
    try {
        Cipher.getInstance("RSA/ECB/NoPadding", p);
    } catch (GeneralSecurityException e) {
        System.out.println("Not supported by provider, skipping");
        return;
    }

    final int KEY_LEN = 1024;
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", p);
    kpGen.initialize(KEY_LEN);
    KeyPair kp = kpGen.generateKeyPair();
    Random random = new Random();
    byte[] plainText, cipherText, recoveredText;
    plainText = new byte[KEY_LEN/8];
    random.nextBytes(plainText);
    plainText[0] = 0; // to ensure that it's less than modulus

    Cipher c1 = Cipher.getInstance("RSA/ECB/NoPadding", p);
    Cipher c2 = Cipher.getInstance("RSA/ECB/NoPadding", "SunJCE");

    c1.init(Cipher.ENCRYPT_MODE, kp.getPublic());
    c2.init(Cipher.DECRYPT_MODE, kp.getPrivate());

    cipherText = c1.doFinal(plainText);
    recoveredText = c2.doFinal(cipherText);
    if (!Arrays.equals(plainText, recoveredText)) {
        throw new RuntimeException("E/D Test against SunJCE Failed!");
    }

    c2.init(Cipher.ENCRYPT_MODE, kp.getPublic());
    c1.init(Cipher.DECRYPT_MODE, kp.getPrivate());
    cipherText = c2.doFinal(plainText);
    recoveredText = c1.doFinal(cipherText);
    if (!Arrays.equals(plainText, recoveredText)) {
        throw new RuntimeException("D/E Test against SunJCE Failed!");
    }

    System.out.println("Test Passed");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:42,代码来源:TestRawRSACipher.java


注:本文中的java.security.KeyPairGenerator.initialize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。