本文整理汇总了Java中java.security.KeyPair类的典型用法代码示例。如果您正苦于以下问题:Java KeyPair类的具体用法?Java KeyPair怎么用?Java KeyPair使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
KeyPair类属于java.security包,在下文中一共展示了KeyPair类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createKeys
import java.security.KeyPair; //导入依赖的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());
}
示例2: generateECKeypair
import java.security.KeyPair; //导入依赖的package包/类
public static KeyPair generateECKeypair(ASN1ObjectIdentifier curveId, SecureRandom random)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidAlgorithmParameterException {
ParamUtil.requireNonNull("curveId", curveId);
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveId.getId());
KeyPairGenerator kpGen = getKeyPairGenerator("EC");
synchronized (kpGen) {
if (random == null) {
kpGen.initialize(spec);
} else {
kpGen.initialize(spec, random);
}
return kpGen.generateKeyPair();
}
}
示例3: ECKey
import java.security.KeyPair; //导入依赖的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: generateKeyPair
import java.security.KeyPair; //导入依赖的package包/类
public KeyPair generateKeyPair()
{
if (!initialised)
{
param = new RainbowKeyGenerationParameters(random, new RainbowParameters(new RainbowParameterSpec().getVi()));
engine.init(param);
initialised = true;
}
AsymmetricCipherKeyPair pair = engine.generateKeyPair();
RainbowPublicKeyParameters pub = (RainbowPublicKeyParameters)pair.getPublic();
RainbowPrivateKeyParameters priv = (RainbowPrivateKeyParameters)pair.getPrivate();
return new KeyPair(new BCRainbowPublicKey(pub),
new BCRainbowPrivateKey(priv));
}
示例5: test
import java.security.KeyPair; //导入依赖的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));
}
示例6: generateKeyPair
import java.security.KeyPair; //导入依赖的package包/类
/**
* Generates RSA KeyPair
*/
public static KeyPair generateKeyPair()
{
try
{
KeyPairGenerator keypairgenerator = KeyPairGenerator.getInstance("RSA");
keypairgenerator.initialize(1024);
return keypairgenerator.generateKeyPair();
}
catch (NoSuchAlgorithmException nosuchalgorithmexception)
{
nosuchalgorithmexception.printStackTrace();
LOGGER.error("Key pair generation failed!");
return null;
}
}
示例7: testKeyAgreement
import java.security.KeyPair; //导入依赖的package包/类
private static void testKeyAgreement(KeyPair kpA, KeyPair kpB, Provider p)
throws Exception {
KeyAgreement ka1 = KeyAgreement.getInstance("ECDH", p);
ka1.init(kpA.getPrivate());
ka1.doPhase(kpB.getPublic(), true);
byte[] s1 = ka1.generateSecret();
KeyAgreement ka2 = KeyAgreement.getInstance("ECDH", p);
ka2.init(kpB.getPrivate());
ka2.doPhase(kpA.getPublic(), true);
byte[] s2 = ka2.generateSecret();
if (Arrays.equals(s1, s2) == false) {
System.out.println("expected: " + toString(s1));
System.out.println("actual: " + toString(s2));
throw new Exception("Generated secrets do not match");
}
}
示例8: testJWEWithRSAAESKey2
import java.security.KeyPair; //导入依赖的package包/类
@Test
public void testJWEWithRSAAESKey2() {
String claimsJSON = sampleClaims();
KeyPair rsaKeyPair = getRSAKeyPair();
String jwt = jweEncrypt(claimsJSON, false, rsaKeyPair.getPublic(), "RSA_OAEP", "AES_128_GCM");
String pemPrivateKey = getPEMPrivateKeyFromDER(rsaKeyPair.getPrivate());
JWTValidator validator =
jweValidator(
pemPrivateKey, "RSA_OAEP", "AES_128_GCM",
jwt, "edge-jwt-gen", "aud-1", "300");
ExecutionResult result = validator.execute(this.mctx, this.ectx);
verifySuccessResult(result);
varifyClaims(this.mctx.getVariable(CLAIMS));
}
示例9: generateEcKeyPair
import java.security.KeyPair; //导入依赖的package包/类
@Override
public KeyPair generateEcKeyPair(final EcCurve curveName) throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME); //$NON-NLS-1$
}
catch (final Exception e) {
Logger.getLogger("es.gob.jmulticard").warning( //$NON-NLS-1$
"No se ha podido obtener un generador de pares de claves de curva eliptica con SpongyCastle, se usara el generador por defecto: " + e //$NON-NLS-1$
);
kpg = KeyPairGenerator.getInstance("EC"); //$NON-NLS-1$
}
Logger.getLogger("es.gob.jmulticard").info( //$NON-NLS-1$
"Seleccionado el siguiente generador de claves de curva eliptica: " + kpg.getClass().getName() //$NON-NLS-1$
);
final AlgorithmParameterSpec parameterSpec = new ECGenParameterSpec(curveName.toString());
kpg.initialize(parameterSpec);
return kpg.generateKeyPair();
}
示例10: testJWEAndJWSWithRSAAndRSA
import java.security.KeyPair; //导入依赖的package包/类
@Test
public void testJWEAndJWSWithRSAAndRSA() {
String claimsJSON = sampleClaims();
KeyPair rsaKeyPairSign = getRSAKeyPair();
String pemPublicKeySign = getPEMPublicKeyFromDER(rsaKeyPairSign.getPublic());
KeyPair rsaKeyPairEnc = getRSAKeyPair();
String pemPrivateKeyEnc = getPEMPrivateKeyFromDER(rsaKeyPairEnc.getPrivate());
String innerJWT = jwsSign(claimsJSON, rsaKeyPairSign.getPrivate(), "RSA_USING_SHA256");
String jwt = jweEncrypt(innerJWT, true, rsaKeyPairEnc.getPublic(), "RSA_OAEP", "AES_128_GCM");
JWTValidator validator =
validatorJWSAndJWE(
pemPublicKeySign, "RSA_USING_SHA256",
pemPrivateKeyEnc, "RSA_OAEP", "AES_128_GCM",
jwt, "edge-jwt-gen", "aud-1", "300");
ExecutionResult result = validator.execute(this.mctx, this.ectx);
verifySuccessResult(result);
varifyClaims(this.mctx.getVariable(CLAIMS));
}
示例11: checkSignatureForToken
import java.security.KeyPair; //导入依赖的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())));
}
示例12: main
import java.security.KeyPair; //导入依赖的package包/类
public static void main(String[] args) throws GeneralSecurityException, UnsupportedEncodingException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
RSAPrivateKeySpec.class);
publicKey = fact.generatePublic(pub);
privateKey = fact.generatePrivate(priv);
String foo = rsaEncrypt("foo");
byte[] decode = Base64.getDecoder().decode("foo");
System.out.println(Base64.getEncoder().encodeToString(decode));
System.out.println(rsaDecrypt(foo));
}
示例13: GameServerThread
import java.security.KeyPair; //导入依赖的package包/类
public GameServerThread(Socket con)
{
_connection = con;
_connectionIp = con.getInetAddress().getHostAddress();
try
{
_in = _connection.getInputStream();
_out = new BufferedOutputStream(_connection.getOutputStream());
}
catch (IOException e)
{
_log.warning(getClass().getSimpleName() + ": " + e.getMessage());
}
final KeyPair pair = GameServerTable.getInstance().getKeyPair();
_privateKey = (RSAPrivateKey) pair.getPrivate();
_publicKey = (RSAPublicKey) pair.getPublic();
_blowfish = new NewCrypt("_;v.]05-31!|+-%xT!^[$\00");
setName(getClass().getSimpleName() + "-" + getId() + "@" + _connectionIp);
start();
}
示例14: AbstractRSSTest
import java.security.KeyPair; //导入依赖的package包/类
public AbstractRSSTest(String algorithm, Provider provider, KeyPair keyPair) {
Security.insertProviderAt(provider, 1);
this.algorithm = algorithm;
this.providerName = provider.getName();
this.provider = provider;
AbstractRSSTest.keyPair = keyPair;
}
示例15: generateCertificate
import java.security.KeyPair; //导入依赖的package包/类
/**
* Create a self-signed X.509 Certificate.
*
* @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
* @param pair the KeyPair
* @param days how many days from now the Certificate is valid for
* @param algorithm the signing algorithm, eg "SHA1withRSA"
* @return the self-signed certificate
*/
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
throws CertificateEncodingException, InvalidKeyException, IllegalStateException,
NoSuchProviderException, NoSuchAlgorithmException, SignatureException {
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000l);
BigInteger sn = new BigInteger(64, new SecureRandom());
KeyPair keyPair = pair;
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
X500Principal dnName = new X500Principal(dn);
certGen.setSerialNumber(sn);
certGen.setIssuerDN(dnName);
certGen.setNotBefore(from);
certGen.setNotAfter(to);
certGen.setSubjectDN(dnName);
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm(algorithm);
X509Certificate cert = certGen.generate(pair.getPrivate());
return cert;
}