本文整理汇总了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));
}
示例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());
}
示例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())));
}
示例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();
}
}
示例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();
}
}
示例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()));
}
}
示例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;
}
示例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();
}
}
示例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;
}
示例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;
}
}
示例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;
}
}
示例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();
}
示例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;
}
示例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;
}
}
示例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");
}