Java 类java.security.KeyPair 实例源码
项目:rebase-android
文件:BlackBox.java
/**
* 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());
}
项目:xitk
文件:KeyUtil.java
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();
}
}
项目:AppCoins-ethereumj
文件:ECKey.java
/**
* 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());
}
}
项目:ipack
文件:RainbowKeyPairGeneratorSpi.java
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));
}
项目:BaseClient
文件:CryptManager.java
/**
* 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;
}
}
项目:openjdk-jdk10
文件:TestECDH2.java
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");
}
}
项目:edge-jwt-sample
文件:JWTValidatorTest.java
@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));
}
项目:mi-firma-android
文件:JseCryptoHelper.java
@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();
}
项目:edge-jwt-sample
文件:JWTValidatorTest.java
@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));
}
项目:firebase-admin-java
文件:FirebaseTokenFactoryTest.java
@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())));
}
项目:BaseClient
文件:CryptManager.java
/**
* 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;
}
}
项目:outcomes
文件:Main.java
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));
}
项目:L2J-Global
文件:GameServerThread.java
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();
}
项目:xmlrss
文件:AbstractRSSTest.java
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;
}
项目:ditb
文件:KeyStoreTestUtil.java
/**
* 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;
}
项目:edge-jwt-sample
文件:JWTValidatorTest.java
@Test
public void testJWEAndJWSWithRSAAndHMAC() {
String claimsJSON = sampleClaims();
SecretKey keySign = getHmacSHA256Key();
KeyPair rsaKeyPairEnc = getRSAKeyPair();
String pemPrivateKeyEnc = getPEMPrivateKeyFromDER(rsaKeyPairEnc.getPrivate());
String innerJWT = jwsSign(claimsJSON, keySign, "HMAC_SHA256");
String jwt = jweEncrypt(innerJWT, true, rsaKeyPairEnc.getPublic(), "RSA_OAEP", "AES_128_GCM");
JWTValidator validator =
validatorJWSAndJWE(
keyToString(keySign), "HMAC_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));
}
项目:openjdk-jdk10
文件:TestKeyFactory.java
@Override
public void main(Provider p) throws Exception {
if (p.getService("KeyFactory", "EC") == null) {
System.out.println("Provider does not support EC, skipping");
return;
}
int[] keyLengths = {192, 163, 409, 521};
int len = 0;
if (getNSSECC() == ECCState.Basic) {
System.out.println("NSS Basic ECC only. Skipping 192, 163, & 409");
len = 3;
}
KeyFactory kf = KeyFactory.getInstance("EC", p);
for (; keyLengths.length > len ; len++) {
System.out.println("Length "+keyLengths[len]);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", p);
kpg.initialize(keyLengths[len]);
KeyPair kp = kpg.generateKeyPair();
test(kf, kp.getPrivate());
test(kf, kp.getPublic());
}
}
项目:Encryption
文件:TestRSA.java
private static void testRSA_Async_decrypt(KeyPair key, String message){
Encoder.BuilderRSA()
.message(message)
.method(RSA.Method.RSA_ECB_OAEP_with_MD5_and_MGF1_PADDING)
.key(key)
.encryptCallBack(new EncodeCallback() {
@Override
public void onSuccess(String result) {
System.out.println("decryptAsync RSA with " + RSA.Method.RSA_ECB_OAEP_with_MD5_and_MGF1_PADDING + " = " + result);
}
@Override
public void onFailure(Throwable e) {
System.out.println("decryptAsync RSA error");
e.printStackTrace();
}
})
.decryptAsync();
}
项目:wolfcrypt-jni
文件:EccTest.java
@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");
}
项目:hadoop-oss
文件:TestReloadingX509TrustManager.java
@Test
public void testReloadMissingTrustStore() throws Exception {
KeyPair kp = generateKeyPair("RSA");
cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
cert2 = generateCertificate("CN=Cert2", kp, 30, "SHA1withRSA");
String truststoreLocation = BASEDIR + "/testmissing.jks";
createTrustStore(truststoreLocation, "password", "cert1", cert1);
ReloadingX509TrustManager tm =
new ReloadingX509TrustManager("jks", truststoreLocation, "password", 10);
try {
tm.init();
assertEquals(1, tm.getAcceptedIssuers().length);
X509Certificate cert = tm.getAcceptedIssuers()[0];
new File(truststoreLocation).delete();
// Wait so that the file modification time is different
Thread.sleep((tm.getReloadInterval() + 200));
assertEquals(1, tm.getAcceptedIssuers().length);
assertEquals(cert, tm.getAcceptedIssuers()[0]);
} finally {
tm.destroy();
}
}
项目:mobile-store
文件:LocalRepoKeyStore.java
public void setupHTTPSCertificate() {
try {
// Get the existing private/public keypair to use for the HTTPS cert
KeyPair kerplappKeypair = getKerplappKeypair();
/*
* Once we have an IP address, that can be used as the hostname. We
* can generate a self signed cert with a valid CN field to stash
* into the keystore in a predictable place. If the IP address
* changes we should run this method again to stomp old
* HTTPS_CERT_ALIAS entries.
*/
X500Name subject = new X500Name("CN=" + FDroidApp.ipAddressString);
Certificate indexCert = generateSelfSignedCertChain(kerplappKeypair, subject,
FDroidApp.ipAddressString);
addToStore(HTTP_CERT_ALIAS, kerplappKeypair, indexCert);
} catch (Exception e) {
Log.e(TAG, "Failed to setup HTTPS certificate", e);
}
}
项目:openjdk-jdk10
文件:SupportedDHKeys.java
@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);
}
}
项目:DecompiledMinecraft
文件:CryptManager.java
/**
* 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;
}
}
项目:edge-jwt-sample
文件:JWTValidatorTest.java
private 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;
}
}
项目:Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud
文件:Utils.java
/**
* Create a random 1024 bit RSA key pair
*/
public static KeyPair generateRSAKeyPair()
throws Exception
{
Security
.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
kpGen.initialize(1024, new SecureRandom());
return kpGen.generateKeyPair();
}
项目:asch-java
文件:TransactionBuilder.java
public TransactionInfo buildSignature(String secret, String secondSecret) throws SecurityException{
KeyPair keyPair = getSecurity().generateKeyPair(secret);
KeyPair secondKeyPair = getSecurity().generateKeyPair(secondSecret);
TransactionInfo transaction = newTransaction(
TransactionType.Signature,
0L,
AschConst.Fees.SECOND_SIGNATURE,
keyPair.getPublic())
.setAsset(new SignatureAssetInfo(getSecurity().encodePublicKey(secondKeyPair.getPublic())));
return signatureAndGenerateTransactionId(transaction, keyPair.getPrivate(), null);
}
项目:openjdk-jdk10
文件:GenerateRSAKeyPair.java
public static void main(String[] args) throws Exception {
RSAKeyGenParameterSpec rsaSpec =
new RSAKeyGenParameterSpec (1024, RSAKeyGenParameterSpec.F4);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
kpg.initialize(rsaSpec);
// test generateKeyPair
KeyPair kpair = kpg.generateKeyPair();
if (kpair == null) {
throw new Exception("no keypair generated");
}
}
项目:crypto-shuffle
文件:JsonUtilTest.java
@Test
public void multiEncryptionSerializationTest() {
Set<KeyPair> keyPairs = generateKeyPairs(3);
final MultiEncryption multiEncryption
= new MultiEncryption(key24, keyPairs.stream().map(KeyPair::getPublic).collect(Collectors.toList()));
final ObjectNode jsonObject = (ObjectNode) JsonUtil.multiEncryptionToJson(multiEncryption);
jsonObject.get(JsonUtil.ENCRYPTION_ALGORITHM_NAME).asText();
assertEquals(JsonUtil.VERSION1_0, jsonObject.get(JsonUtil.VERSION_NAME).asText());
assertEquals("RSA", jsonObject.get(JsonUtil.ENCRYPTION_ALGORITHM_NAME).asText());
final ObjectNode keysObject = (ObjectNode) jsonObject.get(JsonUtil.ENCRYPTIONS_NAME);
assertEquals(3, keysObject.size());
}
项目:Myst
文件:Util.java
public static ECPoint randECPoint() throws Exception {
Security.addProvider(new BouncyCastleProvider());
ECParameterSpec ecSpec_named = ECNamedCurveTable.getParameterSpec("secp256r1"); // NIST P-256
KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDSA", "BC");
kpg.initialize(ecSpec_named);
KeyPair apair = kpg.generateKeyPair();
ECPublicKey apub = (ECPublicKey) apair.getPublic();
return apub.getQ();
}
项目:19porn
文件:Codec.java
/**
* 初始化密钥
*
* @return
* @throws Exception
*/
public static Map<String, Object> initKey() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(Algorithm.RSA.getType());
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;
}
项目:asch-java
文件:TransactionBuilder.java
public TransactionInfo buildInTransfer(String dappId, String currency, long amount, String secret, String secondSecret)throws SecurityException {
KeyPair keyPair = getSecurity().generateKeyPair(secret);
TransactionInfo transaction = newTransaction(
TransactionType.InTransfer,
currency.equals("XAS") ? amount : 0l,
AschConst.Fees.TRANSFER,
keyPair.getPublic())
.setAsset(new InTransferAssetInfo(dappId, currency,currency.equals("XAS") ? 0l : amount));
return signatureAndGenerateTransactionId(transaction, keyPair.getPrivate(), secondSecret);
}
项目:pac4j-plus
文件:JWKHelper.java
/**
* Build the RSA key pair from the JWK JSON.
*
* @param json the json
* @return the key pair
*/
public static KeyPair buildRSAKeyPairFromJwk(final String json) {
CommonHelper.assertNotBlank("json", json);
try {
final RSAKey rsaKey = RSAKey.parse(json);
return rsaKey.toKeyPair();
} catch (final JOSEException | ParseException e) {
throw new TechnicalException(e);
}
}
项目:crypto-shuffle
文件:JsonUtilTest.java
@Before
public void createKeyShardSet() {
try {
keyPairs5 = generateKeyPairs(5);
keyPairs3 = generateKeyPairs(3);
final KeyShardSet.KeyShardingSetBuilder builder = KeyShardSet.newBuilder(AsymmetricEncryptionAlgorithm.RSA);
final Set<PublicKey> publicKeys5 = keyPairs5.stream().map(KeyPair::getPublic).collect(Collectors.toSet());
final Set<PublicKey> publicKeys3 = keyPairs3.stream().map(KeyPair::getPublic).collect(Collectors.toSet());
keyShardSet = builder.addKeyGroup(2, publicKeys5).addKeyGroup(3, publicKeys3).build(key4800);
} catch (Throwable e) {
System.err.println("Before");
e.printStackTrace();
throw e;
}
}
项目:openjdk-jdk10
文件:SignatureTest.java
public static void main(String[] args) throws Exception {
int testSize = Integer.parseInt(args[0]);
byte[] data = new byte[100];
IntStream.range(0, data.length).forEach(j -> {
data[j] = (byte) j;
});
// create a key pair
KeyPair kpair = generateKeys(KEYALG, testSize);
Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());
Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());
// For signature algorithm, create and verify a signature
Arrays.stream(privs).forEach(priv
-> Arrays.stream(pubs).forEach(pub
-> Arrays.stream(SIGN_ALG).forEach(testAlg -> {
try {
checkSignature(data, (PublicKey) pub, (PrivateKey) priv,
testAlg);
} catch (NoSuchAlgorithmException | InvalidKeyException |
SignatureException | NoSuchProviderException ex) {
throw new RuntimeException(ex);
}
}
)));
}
项目:JWaves
文件:Address.java
/**
* Create new address.
*
* @param chain chain.
* @param n world count.
* @return new address.
* @throws IOException
*/
public static Address createNew(@NotNull final String chain, final int n) throws IOException {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
final File file = new File("src/main/resources/words.json");
final ObjectMapper mapper = new ObjectMapper();
final CollectionType type = mapper.getTypeFactory().constructCollectionType(List.class, String.class);
final List<String> wordList = mapper.readValue(file, type);
final StringBuilder words = new StringBuilder();
final Random rand = new Random();
for (int i = 0; i < n; i++) {
int index = rand.nextInt(wordList.size());
words.append(wordList.get(index));
if (i < n - 1) {
words.append(" ");
}
wordList.remove(index);
}
final String seed = words.toString();
byte[] seedEncode = seed.getBytes(StandardCharsets.UTF_8);
final byte[] seedHash = Crypto.hashChain(seedEncode);
final byte[] accountSeedHash = Crypto.sha256(seedHash);
final Curve25519KeyPairGenerator gen = new Curve25519KeyPairGenerator();
final KeyPair pair = gen.generateKeyPair(accountSeedHash);
return generate(pair, seed, chain);
}
项目:GroupControlDroidClient
文件:RSAUtil.java
/**
* 生成公钥和私钥
*
* @throws NoSuchAlgorithmException
*
*/
public static HashMap<String, Object> getKeys()
throws NoSuchAlgorithmException {
HashMap<String, Object> map = new HashMap<String, Object>();
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024,new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
map.put("public", publicKey);
map.put("private", privateKey);
return map;
}
项目:openjdk-jdk10
文件:Correctness.java
public static void main(String[] args) throws Exception {
String SIGALG = "SHA1withRSA";
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
KeyPair kp = kpg.generateKeyPair();
SignedObject so1 = new SignedObject("Hello", kp.getPrivate(),
Signature.getInstance(SIGALG));
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(so1);
out.close();
byte[] data = byteOut.toByteArray();
SignedObject so2 = (SignedObject)new ObjectInputStream(
new ByteArrayInputStream(data)).readObject();
if (!so2.getObject().equals("Hello")) {
throw new Exception("Content changed");
}
if (!so2.getAlgorithm().equals(SIGALG)) {
throw new Exception("Signature algorithm unknown");
}
if (!so2.verify(kp.getPublic(), Signature.getInstance(SIGALG))) {
throw new Exception("Not verified");
}
}
项目:Spring-Security-Third-Edition
文件:OAuth2AuthorizationServerConfig.java
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
KeyPair keyPair = new KeyStoreKeyFactory(
new ClassPathResource(keystore),
keyStorePass.toCharArray()
).getKeyPair(keyPairAlias);
converter.setKeyPair(keyPair);
return converter;
}
项目:openjdk-jdk10
文件:Offsets.java
static Offsets init(String provider, String algorithm)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, SignatureException {
// fill the cleartext data with random bytes
byte[] cleartext = new byte[100];
RandomFactory.getRandom().nextBytes(cleartext);
// NONEwith requires input to be of 20 bytes
int size = algorithm.contains("NONEwith") ? 20 : 100;
// create signature instance
Signature signature = Signature.getInstance(algorithm, provider);
String keyAlgo;
if (algorithm.contains("RSA")) {
keyAlgo = "RSA";
} else if (algorithm.contains("ECDSA")) {
keyAlgo = "EC";
} else if (algorithm.contains("DSA")) {
keyAlgo = "DSA";
} else {
throw new RuntimeException("Test doesn't support this signature "
+ "algorithm: " + algorithm);
}
KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo, provider);
KeyPair kp = kpg.generateKeyPair();
PublicKey pubkey = kp.getPublic();
PrivateKey privkey = kp.getPrivate();
return new Offsets(signature, pubkey, privkey, size, cleartext);
}
项目:LotusCloud
文件:PacketClient.java
public static Packet request(String host, int port, Packet packet) {
KeyPair keyPair = Crypter.generateKeyPair();
try {
Socket socket = new Socket(host, port);
if (socket.isClosed()) {
return new ErrorPacket("socket closed");
}
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
out.writeObject(keyPair.getPublic());
PublicKey publicKey = (PublicKey) in.readObject();
SecretKey key = Crypter.generateEC(keyPair.getPrivate(), publicKey);
out.writeObject(Crypter.encrypt(key, Crypter.toByteArray(packet)));
out.flush();
Packet response = (Packet) Crypter.toObject(Crypter.decrypt(key, (byte[]) in.readObject()));
in.close();
out.close();
socket.close();
return response;
} catch (Exception ex) {
return new ErrorPacket(ex.getMessage());
}
}