本文整理汇总了Java中java.security.KeyPairGenerator.genKeyPair方法的典型用法代码示例。如果您正苦于以下问题:Java KeyPairGenerator.genKeyPair方法的具体用法?Java KeyPairGenerator.genKeyPair怎么用?Java KeyPairGenerator.genKeyPair使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.security.KeyPairGenerator
的用法示例。
在下文中一共展示了KeyPairGenerator.genKeyPair方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: 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");
}
}
示例2: wrapperPublicPriviteKeyTest
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
private void wrapperPublicPriviteKeyTest(Provider p, String[] algorithms)
throws NoSuchAlgorithmException, InvalidKeyException,
NoSuchPaddingException, IllegalBlockSizeException,
InvalidAlgorithmParameterException {
for (String algo : algorithms) {
// Key pair generated
System.out.println("Generate key pair (algorithm: " + algo
+ ", provider: " + p.getName() + ")");
KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);
kpg.initialize(512);
KeyPair kp = kpg.genKeyPair();
// key generated
String algoWrap = "DES";
KeyGenerator kg = KeyGenerator.getInstance(algoWrap, p);
Key key = kg.generateKey();
wrapTest(algo, algoWrap, key, kp.getPrivate(), Cipher.PRIVATE_KEY,
false);
wrapTest(algo, algoWrap, key, kp.getPublic(), Cipher.PUBLIC_KEY,
false);
}
}
示例3: getEccCurveNameFromSpec
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@Test
public void getEccCurveNameFromSpec()
throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
/* generate key pair */
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec genSpec = new ECGenParameterSpec("secp256r1");
kpg.initialize(genSpec);
KeyPair pair = kpg.genKeyPair();
ECPrivateKey priv = (ECPrivateKey)pair.getPrivate();
ECParameterSpec spec = priv.getParams();
String curveName = Ecc.getCurveName(spec);
assertEquals(curveName, "SECP256R1");
}
示例4: Auth
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
public Auth(String clientId, String clientSecret, String callbackURL) throws NoSuchAlgorithmException {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.gson = new Gson();
this.authUsers = new ArrayList<>();
// TODO: this is where authorized users are hardcoded
// The email address must be one managed by Google
//authUsers.add("[email protected]");
this.globalService = new ServiceBuilder()
.apiKey(clientId)
.apiSecret(clientSecret)
.scope("email") // replace with desired scope
.callback(callbackURL)
.build(GoogleApi20.instance());
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
this.keyPair = keyPairGenerator.genKeyPair();
this.callbackURL = callbackURL;
}
示例5: testJWTAuthentication_signed_asymmetric
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@Test
public void testJWTAuthentication_signed_asymmetric() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
KeyPair keyPair = keyGen.genKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
final JwtConfiguration cfg = JwtConfiguration.builder().signatureAlgorithm(SignatureAlgorithm.RS256.getValue())
.privateKey(privateKey).publicKey(publicKey).build();
final Realm realm = Realm.builder().authenticator(JwtAuthenticator.builder().configuration(cfg).build())
.build();
Authentication authc = Authentication.builder("testuser").root(true).build();
String jwt = JwtTokenBuilder.buildJWT(authc, "TestId", "TestUnit", 20000L, SignatureAlgorithm.RS256,
privateKey);
assertNotNull(jwt);
Authentication authenticated = realm.authenticate(AuthenticationToken.bearer(jwt));
assertNotNull(authenticated);
assertEquals(authc, authenticated);
assertEquals("TestUnit", authenticated.getParameter(Claims.ISSUER, String.class).get());
assertEquals("TestId", authenticated.getParameter(Claims.ID, String.class).get());
}
示例6: failsWhenUidIsTooLong
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@Test
public void failsWhenUidIsTooLong() 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);
thrown.expect(IllegalStateException.class);
tokenFactory.createSignedCustomAuthTokenForUser(
Strings.repeat("a", 129), ISSUER, keys.getPrivate());
}
示例7: 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;
}
}
示例8: failsWhenExtraClaimsContainsReservedKey
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@Test
public void failsWhenExtraClaimsContainsReservedKey() 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);
Map<String, Object> extraClaims = ImmutableMap.<String, Object>of("iss", "repeat issuer");
thrown.expect(IllegalArgumentException.class);
tokenFactory.createSignedCustomAuthTokenForUser(
USER_ID, extraClaims, ISSUER, keys.getPrivate());
}
示例9: generateKeyPair
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
/**
* 生成密钥对
*
* @return KeyPair
*/
public static KeyPair generateKeyPair() {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.genKeyPair();
return keyPair;
} catch (Exception e) {
throw new RuntimeException("Error when init key pair, errmsg: " + e.getMessage(), e);
}
}
示例10: generateKeyPair
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
/**
* Generate a new RSA keypair.
* @param keySize - the size of the key
* @return KeyPair
* @throws NoSuchAlgorithmException on failure to load RSA key generator
*/
public static KeyPair generateKeyPair(int keySize) throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(keySize);
KeyPair keyPair = keyPairGenerator.genKeyPair();
return keyPair;
}
示例11: call
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
@Override
public Certificate call() {
try {
final String url = REMOTE_ADDRESS+"/Register";
RestTemplate restTemplate = new RestTemplate();
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.YEAR, 10);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
.setAlias(context.getString(R.string.key_key))
.setKeySize(2048)
.setSubject(new X500Principal(""))
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.setSerialNumber(BigInteger.ONE)
.build();
kpg.initialize(spec);
KeyPair keyPair = kpg.genKeyPair();
byte[] pub = keyPair.getPublic().getEncoded();
RegistrationData device = new RegistrationData();
device.setDeviceToken(FirebaseInstanceId.getInstance().getToken());
device.setDeviceDescription(getDeviceName());
device.setPublicKey(pub);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Log.d(getClass().getName(), "Public key is: "+ Bytes.hexString(pub));
return restTemplate.postForObject(url, device, Certificate.class);
} catch (Exception e) {
Log.e(getClass().getName(), e.getMessage(), e);
}
return null;
}
示例12: XMLDSigWithSecMgr
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
XMLDSigWithSecMgr() throws Exception {
setup();
Document doc = db.newDocument();
Element envelope = doc.createElementNS
("http://example.org/envelope", "Envelope");
envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
"xmlns", "http://example.org/envelope");
doc.appendChild(envelope);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
KeyPair kp = kpg.genKeyPair();
// the policy only grants this test SocketPermission to accept, resolve
// and connect to localhost so that it can dereference 2nd reference
System.setProperty("java.security.policy",
System.getProperty("test.src", ".") + File.separator + "policy");
System.setSecurityManager(new SecurityManager());
try {
// generate a signature with SecurityManager enabled
ArrayList refs = new ArrayList();
refs.add(fac.newReference
("", sha1,
Collections.singletonList
(fac.newTransform(Transform.ENVELOPED,
(TransformParameterSpec) null)), null, null));
refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
+ "/anything.txt", sha1));
SignedInfo si = fac.newSignedInfo(withoutComments,
fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
XMLSignature sig = fac.newXMLSignature(si, null);
DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
sig.sign(dsc);
// validate a signature with SecurityManager enabled
DOMValidateContext dvc = new DOMValidateContext
(kp.getPublic(), envelope.getFirstChild());
// disable secure validation mode so that http reference will work
dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
sig = fac.unmarshalXMLSignature(dvc);
if (!sig.validate(dvc)) {
throw new Exception
("XMLDSigWithSecMgr signature validation FAILED");
}
} catch (SecurityException se) {
throw new Exception("XMLDSigWithSecMgr FAILED", se);
}
ss.close();
}
示例13: generateKeyPair
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
public static KeyPair generateKeyPair(String algorithm)
throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
keyGen.initialize(1024);
return keyGen.genKeyPair();
}
示例14: jwtRSAEncryption
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
/**
* 使用RSA 算法进行加密数据
* 与解密数据
* <p/>
* 128
* RSA_OAEP - A128GCM
* 256
* RSA_OAEP_256 - A256GCM
*
* @throws Exception
*/
@Test
public void jwtRSAEncryption() throws Exception {
// RSA keyPair Generator
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
/**
* 长度 至少 1024, 建议 2048
*/
final int keySize = 2048;
keyPairGenerator.initialize(keySize);
final KeyPair keyPair = keyPairGenerator.genKeyPair();
//公钥
final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
//私钥
final PrivateKey privateKey = keyPair.getPrivate();
//加密, 生成idToken
//加密的数据放在 JWTClaimsSet 中
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.issuer("https://myoidc.cc")
.subject("Lims")
.audience("https://one-app.com")
.notBeforeTime(new Date())
.issueTime(new Date())
.expirationTime(new Date(new Date().getTime() + 1000 * 60 * 10))
.jwtID(RandomStringUtils.random(16, true, true))
.build();
// JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM);
JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A256GCM);
EncryptedJWT jwt = new EncryptedJWT(header, claimsSet);
RSAEncrypter encrypter = new RSAEncrypter(publicKey);
jwt.encrypt(encrypter);
final String idToken = jwt.serialize();
assertNotNull(idToken);
//解密
final EncryptedJWT parseJWT = EncryptedJWT.parse(idToken);
RSADecrypter decrypter = new RSADecrypter(privateKey);
parseJWT.decrypt(decrypter);
final JWTClaimsSet jwtClaimsSet = parseJWT.getJWTClaimsSet();
assertNotNull(jwtClaimsSet);
assertNotNull(jwtClaimsSet.getAudience());
}
示例15: main
import java.security.KeyPairGenerator; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
// Genererate Keys
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(4096);
KeyPair keyPair = keyPairGenerator.genKeyPair();
System.out.println("Private Key Format = " + new String(keyPair.getPrivate().getFormat()));
System.out.println("Private Key = " + Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
System.out.println("Public Key Format = " + new String(keyPair.getPublic().getFormat()));
System.out.println("Public Key = " + Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
/*
// Load Keys from Base64
Private Key Format = PKCS#8
Private Key = MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANTNa+aaWN0o2bq7Y6YJAZbqMNC11P9i2tDH7pxUS8dDDVI0DKg8PFJEFGJ4Al3kkXMvCQKNTZGfvkwZHLINWgIlxkabtwPBVHo7+kQ+q44ygmNyhK8tFihMSP+U4saHZR7GZL2wWjFyMHL+NhPY83RDJ8JGuBvg0KKYFAWF2UaPAgMBAAECgYEApWU33RbPxKzwdUMaEz1iv+IrqLv63bf+rFEIsvaNo0UJQH/16nhOxf3l/haaeFGjfuvqy9H5nRqUdF78P6NC9YeGP+5VqF78UQaWIYRLLEuss4vHopLJc2Zd5Gqs8Wm2EhuRKUNeI3N3ru4Exns5GRp6jnQXZ8hT4OPDb65sgpkCQQDp/dlKcJC1rz+sPIdiCEj2Bb9WunRK9y7j3Scly46dZwTR5AZHKjzFS1uL32QZ8JEZgzuYyyRSjxIfsecFk/xbAkEA6NFe5T4IWq7X1G7oRIhzIf7t4ARbWRJnW8zLZi7icRQ9s1Tpi7e6pjcD8q3pfN0U3r/qyQ5DgIwhm4mHhCUE3QJBAODuE636LTFpiISyHtY+7pwJBFiDnfzeRmXmlpY/ahWnDTwSvXI1iPuDKDp6AMjqtyDWRTjotj7ip2JuaoyzKBcCQQDlT8Mt++lymB/RBuQTDGqKI3PcX64xjyTqkE4OeUNjqVIUXiAiE3bt2+YxkwYUjBTQSStRmJD3/g3kCpPFnkipAkAHZ0s1GJCuq8qLabde3OkUl4EVRK+BZWnifpy3B8ctAS/eu/Lw9l1n6iu8bsNJVNePlIBB97RB983jxyPfQeyP
Public Key Format = X.509
Public Key = MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDUzWvmmljdKNm6u2OmCQGW6jDQtdT/YtrQx+6cVEvHQw1SNAyoPDxSRBRieAJd5JFzLwkCjU2Rn75MGRyyDVoCJcZGm7cDwVR6O/pEPquOMoJjcoSvLRYoTEj/lOLGh2UexmS9sFoxcjBy/jYT2PN0QyfCRrgb4NCimBQFhdlGjwIDAQAB
*/
/* KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] publicKeyBytes = Base64.getDecoder().decode("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDUzWvmmljdKNm6u2OmCQGW6jDQtdT/YtrQx+6cVEvHQw1SNAyoPDxSRBRieAJd5JFzLwkCjU2Rn75MGRyyDVoCJcZGm7cDwVR6O/pEPquOMoJjcoSvLRYoTEj/lOLGh2UexmS9sFoxcjBy/jYT2PN0QyfCRrgb4NCimBQFhdlGjwIDAQAB");
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKeyBytes);
PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
byte[] privateKeyBytes = Base64.getDecoder().decode("MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANTNa+aaWN0o2bq7Y6YJAZbqMNC11P9i2tDH7pxUS8dDDVI0DKg8PFJEFGJ4Al3kkXMvCQKNTZGfvkwZHLINWgIlxkabtwPBVHo7+kQ+q44ygmNyhK8tFihMSP+U4saHZR7GZL2wWjFyMHL+NhPY83RDJ8JGuBvg0KKYFAWF2UaPAgMBAAECgYEApWU33RbPxKzwdUMaEz1iv+IrqLv63bf+rFEIsvaNo0UJQH/16nhOxf3l/haaeFGjfuvqy9H5nRqUdF78P6NC9YeGP+5VqF78UQaWIYRLLEuss4vHopLJc2Zd5Gqs8Wm2EhuRKUNeI3N3ru4Exns5GRp6jnQXZ8hT4OPDb65sgpkCQQDp/dlKcJC1rz+sPIdiCEj2Bb9WunRK9y7j3Scly46dZwTR5AZHKjzFS1uL32QZ8JEZgzuYyyRSjxIfsecFk/xbAkEA6NFe5T4IWq7X1G7oRIhzIf7t4ARbWRJnW8zLZi7icRQ9s1Tpi7e6pjcD8q3pfN0U3r/qyQ5DgIwhm4mHhCUE3QJBAODuE636LTFpiISyHtY+7pwJBFiDnfzeRmXmlpY/ahWnDTwSvXI1iPuDKDp6AMjqtyDWRTjotj7ip2JuaoyzKBcCQQDlT8Mt++lymB/RBuQTDGqKI3PcX64xjyTqkE4OeUNjqVIUXiAiE3bt2+YxkwYUjBTQSStRmJD3/g3kCpPFnkipAkAHZ0s1GJCuq8qLabde3OkUl4EVRK+BZWnifpy3B8ctAS/eu/Lw9l1n6iu8bsNJVNePlIBB97RB983jxyPfQeyP");
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(privKeySpec);
KeyPair keyPair = new KeyPair(publicKey, privateKey);
System.out.println("Private Key Format = " + new String(keyPair.getPrivate().getFormat()));
System.out.println("Private Key = " + Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
System.out.println("Public Key Format = " + new String(keyPair.getPublic().getFormat()));
System.out.println("Public Key = " + Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
*/
// Init
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
char[] pText = new char[255];
Arrays.fill(pText, 'A');
byte[] plainText = new String(pText).getBytes();
System.out.println("Plain = " + new String(plainText));
// Encode
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] cipherText = cipher.doFinal(plainText);
//byte[] cipherText = Base64.getDecoder().decode("JnyTc+dK18IwjGCaQlFyhwqY5VDK+osXBt9i8nDNPGZAH/yEKyijTBZKlqRtYqFdCM/izCIh2UzfQj+gPpIOC6XwST7hOqTmkc2NY9yyzfp/69GSLJ8yh74TdE2os1plK4NiU3yK8kqo48vFeXuyfpQU+xkyln7JnOU7iSGDwAM=");
//byte[] cipherText = Base64.getDecoder().decode("B6zehJfpUN8oiAj40hwckbU4B8/nafVHpuhFV0K6D6Xu43seMyNl6/DEqNLaBw5/Ek95li5OtbOxqs6fWMkOjcNki9dhOtgJoPloAINC7WhB6gLLuLcHQ0Gb7B5LjaRqdFQGZcNGdJd8BtaKHqM/o7jrJDNZrFBAV/TSAy3v1FE=");
System.out.println("Encrypted Base64 = " + Base64.getEncoder().encodeToString(cipherText));
// Decode
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
byte[] decryptedText = cipher.doFinal(cipherText);
System.out.println("Decrypted = " + new String(decryptedText));
}