本文整理汇总了Java中java.security.KeyPairGenerator类的典型用法代码示例。如果您正苦于以下问题:Java KeyPairGenerator类的具体用法?Java KeyPairGenerator怎么用?Java KeyPairGenerator使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
KeyPairGenerator类属于java.security包,在下文中一共展示了KeyPairGenerator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: signatureTest
import java.security.KeyPairGenerator; //导入依赖的package包/类
private void signatureTest(ValueSigner signer, KeyPairGenerator generator) throws Exception {
byte[] data = "HELLO".getBytes();
Signature signature = signer.getInstance(null);
KeyPair pair = generator.generateKeyPair();
signature.initSign(pair.getPrivate());
signature.update(data);
byte[] digest = signature.sign();
assertThat("digest has a value", TestUtils.wrap(digest), is(not(emptyArray())));
signature.initVerify(pair.getPublic());
signature.update(data);
assertThat("verification succeeds", signature.verify(digest), is(true));
switch (signer) {
case RSA_PKCS1:
break;
default:
signature.initSign(pair.getPrivate());
signature.update(data);
assertThat("signatures correctly use random padding", signature.sign(), not(equalTo(digest)));
}
}
示例2: ECKey
import java.security.KeyPairGenerator; //导入依赖的package包/类
/**
* Generate a new keypair using the given Java Security Provider.
*
* All private key operations will use the provider.
*/
public ECKey(Provider provider, SecureRandom secureRandom) {
this.provider = provider;
final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
final KeyPair keyPair = keyPairGen.generateKeyPair();
this.privKey = keyPair.getPrivate();
final PublicKey pubKey = keyPair.getPublic();
if (pubKey instanceof BCECPublicKey) {
pub = ((BCECPublicKey) pubKey).getQ();
} else if (pubKey instanceof ECPublicKey) {
pub = extractPublicKey((ECPublicKey) pubKey);
} else {
throw new AssertionError(
"Expected Provider " + provider.getName() +
" to produce a subtype of ECPublicKey, found " + pubKey.getClass());
}
}
示例3: ECKey
import java.security.KeyPairGenerator; //导入依赖的package包/类
/**
* Generate a new keypair using the given Java Security Provider.
*
* All private key operations will use the provider.
*/
public ECKey(Provider provider, SecureRandom secureRandom) {
this.provider = provider;
final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
final KeyPair keyPair = keyPairGen.generateKeyPair();
this.privKey = keyPair.getPrivate();
final PublicKey pubKey = keyPair.getPublic();
if (pubKey instanceof BCECPublicKey) {
pub = ((BCECPublicKey) pubKey).getQ();
} else if (pubKey instanceof ECPublicKey) {
pub = extractPublicKey((ECPublicKey) pubKey);
} else {
throw new AssertionError(
"Expected Provider " + provider.getName() +
" to produce a subtype of ECPublicKey, found " + pubKey.getClass());
}
}
示例4: 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())));
}
示例5: testInvalidPrivateKey
import java.security.KeyPairGenerator; //导入依赖的package包/类
@Test(expected = IllegalArgumentException.class)
public void testInvalidPrivateKey() throws Exception {
new ECKey(
Security.getProvider("SunEC"),
KeyPairGenerator.getInstance("RSA").generateKeyPair().getPrivate(),
ECKey.fromPublicOnly(pubKey).getPubKeyPoint());
fail("Expecting an IllegalArgumentException for using an non EC private key");
}
示例6: run
import java.security.KeyPairGenerator; //导入依赖的package包/类
@Override
public void run() {
SecureRandom random = new SecureRandom();
// Work around JVM bug
random.nextInt();
random.setSeed(entropy);
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(keyType);
keyPairGen.initialize(numBits, random);
listener.onGenerationSuccess(keyPairGen.generateKeyPair());
} catch (Exception e) {
listener.onGenerationError(e);
}
}
示例7: test
import java.security.KeyPairGenerator; //导入依赖的package包/类
@Test
public void test() throws IOException, NoSuchAlgorithmException {
EnkanSystem system = EnkanSystem.of(
"jsonWebToken", new JsonWebToken(),
"config", new BouncrConfiguration()
).relationships(
component("jsonWebToken").using("config")
);
system.start();
JsonWebToken jsonWebToken = (JsonWebToken)system.getComponent("jsonWebToken");
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair kp = keyGen.generateKeyPair();
JwtHeader header = builder(new JwtHeader())
.set(JwtHeader::setAlg, "RS256")
.set(JwtHeader::setKid, "keyid")
.build();
JwtClaim payload = builder(new JwtClaim())
.set(JwtClaim::setSub, "kawasima")
.set(JwtClaim::setIss, "https://localhost:3002")
.build();
String sign = jsonWebToken.sign(payload, header, kp.getPrivate());
System.out.println(sign);
}
示例8: main
import java.security.KeyPairGenerator; //导入依赖的package包/类
@Override
public void main(Provider provider) throws Exception {
if (provider.getService("KeyPairGenerator", "DiffieHellman") == null) {
System.out.println("No support of DH KeyPairGenerator, skipping");
return;
}
for (SupportedKeySize keySize : SupportedKeySize.values()) {
System.out.println("Checking " + keySize.primeSize + " ...");
KeyPairGenerator kpg =
KeyPairGenerator.getInstance("DiffieHellman", provider);
kpg.initialize(keySize.primeSize);
KeyPair kp = kpg.generateKeyPair();
checkKeyPair(kp, keySize.primeSize, provider);
DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
BigInteger p = publicKey.getParams().getP();
BigInteger g = publicKey.getParams().getG();
kpg.initialize(new DHParameterSpec(p, g));
kp = kpg.generateKeyPair();
checkKeyPair(kp, keySize.primeSize, provider);
}
}
示例9: main
import java.security.KeyPairGenerator; //导入依赖的package包/类
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");
}
}
示例10: generateAuthenticationKey
import java.security.KeyPairGenerator; //导入依赖的package包/类
/**
* Generate a new RSA key pair entry in the Android Keystore by
* using the KeyPairGenerator API. This creates both a KeyPair
* and a self-signed certificate, both with the same alias
*/
private void generateAuthenticationKey() throws GeneralSecurityException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, keystoreName);
kpg.initialize(new KeyGenParameterSpec.Builder(
keyAlias,
KeyProperties.PURPOSE_SIGN)
.setKeySize(2048)
.setCertificateSubject(new X500Principal("CN=unused"))
.setDigests(KeyProperties.DIGEST_SHA256)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.build());
kpg.generateKeyPair();
}
示例11: testKeyPairGeneratorEccMultipleInits
import java.security.KeyPairGenerator; //导入依赖的package包/类
@Test
public void testKeyPairGeneratorEccMultipleInits()
throws NoSuchProviderException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
if (enabledCurves.size() > 0) {
KeyPairGenerator kpg =
KeyPairGenerator.getInstance("EC", "wolfJCE");
ECGenParameterSpec ecSpec =
new ECGenParameterSpec(enabledCurves.get(0));
kpg.initialize(ecSpec);
kpg.initialize(ecSpec);
}
}
示例12: testKeyPairGeneratorEccInitializeWithKeySize
import java.security.KeyPairGenerator; //导入依赖的package包/类
@Test
public void testKeyPairGeneratorEccInitializeWithKeySize()
throws NoSuchProviderException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
/* try initializing KPG for all supported key sizes */
for (int i = 0; i < enabledKeySizes.size(); i++) {
KeyPairGenerator kpg =
KeyPairGenerator.getInstance("EC", "wolfJCE");
kpg.initialize(enabledKeySizes.get(i));
/* bad key size should fail */
try {
kpg.initialize(9999);
} catch (WolfCryptException e) {}
}
}
示例13: createInstance
import java.security.KeyPairGenerator; //导入依赖的package包/类
@Override
protected KeyPair createInstance() throws Exception {
if (secureRandom == null) {
final SecureRandomFactory secureRandomFactory = new SecureRandomFactory();
secureRandomFactory.setProvider(provider);
secureRandomFactory.afterPropertiesSet();
secureRandom = secureRandomFactory.createInstance();
}
final KeyPairGenerator kpg;
if (provider == null) {
kpg = KeyPairGenerator.getInstance(algorithm);
} else {
kpg = KeyPairGenerator.getInstance(algorithm, provider);
}
kpg.initialize(keySize, secureRandom);
return kpg.generateKeyPair();
}
示例14: 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();
}
}
示例15: main
import java.security.KeyPairGenerator; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
TestJCAProvider d = new TestJCAProvider();
// Add dynamically the desired provider
Security.addProvider(new PaillierProvider());
/////////////////////////////////////////////////////////////////////
KeyPairGenerator kpg = KeyPairGenerator.getInstance("Paillier");
kpg.initialize(32);
KeyPair keyPair = kpg.generateKeyPair();
PublicKey pubKey = keyPair.getPublic();
PrivateKey privKey = keyPair.getPrivate();
final Cipher cipher = Cipher.getInstance("Paillier");
final Cipher cipherHP = Cipher.getInstance("PaillierHP");
System.out.println("The Paillier public key through Generator is \n"+keyPair.toString());
System.out.println("The Paillier public key is \n"+keyPair.getPublic().toString());
System.out.println("The Paillier private key is \n"+keyPair.getPrivate().toString());
String plainText = "101";
String plaintext1 = "101";
// get the n
String delims = "[,]";
String[] keyComponents = pubKey.toString().split(delims);
String keyComponent = "";
for (String keyComponent2 : keyComponents) {
if (keyComponent2.startsWith("n")) {
keyComponent = keyComponent2.substring(2);// ignoring 'n:' or 'r:'
}
}
BigInteger n = new BigInteger(keyComponent);
BigInteger first = new BigInteger(plainText);
BigInteger second = new BigInteger(plaintext1);
BigInteger n2 = n.multiply(n);
// encrypt
BigInteger codedBytes = d.encrypt(first.toByteArray(), pubKey,cipherHP);
BigInteger codedBytes12 = d.encrypt(second.toByteArray(), pubKey,cipherHP);
//product
BigInteger product = codedBytes.multiply(codedBytes12);
// product mod n^2
BigInteger tallyProduct = product.mod(n2);
System.out.println(" Product mod n^2: "+tallyProduct);
d.decrypt(tallyProduct.toByteArray(), privKey,cipherHP);
d.decrypt(codedBytes.toByteArray(),privKey,cipherHP);
d.decrypt(codedBytes12.toByteArray(),privKey,cipherHP);
//////////////////////////////BLOCK EXAMPLE/////////////////////////////////
String plainTextBlock = "This Provider working correctly and its safe 10000000000000000011000000000000000001";
System.out.println("This is the message which will be encrypted: " + plainTextBlock);
// encrypt
byte[] codedBytesBlock = d.encryptBlock(plainTextBlock.getBytes(), pubKey,cipher);
String codedMessageBlock = new String(codedBytesBlock);
String codedMessageBlockInHEX = formatingHexRepresentation(codedBytesBlock);
System.out.println("\n" + "ENCRYPTED : \n" + codedMessageBlock);
System.out.println("\n" + "ENCRYPTED in HEX: \n" + codedMessageBlockInHEX);
// decrypt
byte[] encodedBytesBlock = d.decryptBlock(codedMessageBlock, privKey,cipher);
String encodedMessageBlock = new String(encodedBytesBlock);
System.out.println("\n" + "DECRYPTED: \n" + encodedMessageBlock);
}