Java Code Examples for java.security.KeyPair#getPublic()
The following examples show how to use
java.security.KeyPair#getPublic() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RSAUtils.java From AthenaServing with Apache License 2.0 | 6 votes |
public static Map<String, String> createKeys(int keySize) { // 为RSA算法创建一个KeyPairGenerator对象 KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]"); } // 初始化KeyPairGenerator对象,密钥长度 kpg.initialize(keySize); // 生成密匙对 KeyPair keyPair = kpg.generateKeyPair(); // 得到公钥 Key publicKey = keyPair.getPublic(); String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded()); // 得到私钥 Key privateKey = keyPair.getPrivate(); String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded()); Map<String, String> keyPairMap = new HashMap<String, String>(); keyPairMap.put("publicKey", publicKeyStr); keyPairMap.put("privateKey", privateKeyStr); return keyPairMap; }
Example 2
Source File: AsymmetricKeyEncryptionClientDemo.java From markdown-image-kit with MIT License | 6 votes |
private static void buildAndSaveAsymKeyPair() throws IOException, NoSuchAlgorithmException { KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA"); keyGenerator.initialize(1024, srand); KeyPair keyPair = keyGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); FileOutputStream fos = new FileOutputStream(pubKeyPath); fos.write(x509EncodedKeySpec.getEncoded()); fos.close(); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); fos = new FileOutputStream(priKeyPath); fos.write(pkcs8EncodedKeySpec.getEncoded()); fos.close(); }
Example 3
Source File: EncrypRSA.java From ProjectStudy with MIT License | 6 votes |
/** * 测试 * * @param args * @return void * @author Wang926454 * @date 2018/8/21 15:13 */ public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { EncrypRSA rsa = new EncrypRSA(); String msg = "dhdslkaflkf"; // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); // 初始化密钥对生成器,密钥大小为1024位 keyPairGen.initialize(1024); // 生成一个密钥对,保存在keyPair中 KeyPair keyPair = keyPairGen.generateKeyPair(); // 得到私钥 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到公钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 用公钥加密 byte[] srcBytes = msg.getBytes(); byte[] resultBytes = rsa.encrypt(publicKey, srcBytes); // 用私钥解密 byte[] decBytes = rsa.decrypt(privateKey, resultBytes); System.out.println("明文是:" + msg); System.out.println("加密后是:" + new String(resultBytes)); System.out.println("解密后是:" + new String(decBytes)); }
Example 4
Source File: RSAUtil.java From anyline with Apache License 2.0 | 6 votes |
/** * * @param keySize 密钥长度 * @return return */ public static Map<String, String> createKeys(int keySize) { // 为RSA算法创建一个KeyPairGenerator对象 KeyPairGenerator kpg = null; try { kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // 初始化KeyPairGenerator对象,密钥长度 kpg.initialize(keySize); // 生成密匙对 KeyPair keyPair = kpg.generateKeyPair(); // 得到公钥 Key publicKey = keyPair.getPublic(); String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded()); // 得到私钥 Key privateKey = keyPair.getPrivate(); String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded()); Map<String, String> keys = new HashMap<String, String>(); keys.put("public", publicKeyStr); keys.put("private", privateKeyStr); return keys; }
Example 5
Source File: HTTPJwtAuthenticatorTest.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
@Test public void testRS256() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); String jwsToken = Jwts.builder().setSubject("Leonard McCoy").signWith(SignatureAlgorithm.RS256, priv).compact(); Settings settings = Settings.builder().put("signing_key", "-----BEGIN PUBLIC KEY-----\n"+BaseEncoding.base64().encode(pub.getEncoded())+"-----END PUBLIC KEY-----").build(); HTTPJwtAuthenticator jwtAuth = new HTTPJwtAuthenticator(settings, null); Map<String, String> headers = new HashMap<String, String>(); headers.put("Authorization", "Bearer "+jwsToken); AuthCredentials creds = jwtAuth.extractCredentials(new FakeRestRequest(headers, new HashMap<String, String>()), null); Assert.assertNotNull(creds); Assert.assertEquals("Leonard McCoy", creds.getUsername()); Assert.assertEquals(0, creds.getBackendRoles().size()); }
Example 6
Source File: HTTPJwtAuthenticatorTest.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
@Test public void testES512() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC"); keyGen.initialize(571); KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); String jwsToken = Jwts.builder().setSubject("Leonard McCoy").signWith(SignatureAlgorithm.ES512, priv).compact(); Settings settings = Settings.builder().put("signing_key", BaseEncoding.base64().encode(pub.getEncoded())).build(); HTTPJwtAuthenticator jwtAuth = new HTTPJwtAuthenticator(settings, null); Map<String, String> headers = new HashMap<String, String>(); headers.put("Authorization", "Bearer "+jwsToken); AuthCredentials creds = jwtAuth.extractCredentials(new FakeRestRequest(headers, new HashMap<String, String>()), null); Assert.assertNotNull(creds); Assert.assertEquals("Leonard McCoy", creds.getUsername()); Assert.assertEquals(0, creds.getBackendRoles().size()); }
Example 7
Source File: CryptographicUtilities.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
/** * Generates Public Key from BASE64 encoded string */ public static PublicKey getPublicKeyFromString(String keyString) throws Exception { Security.addProvider(new BouncyCastleProvider()); try (PEMReader pemReader = new PEMReader(new StringReader(keyString))) { Object readObject = pemReader.readObject(); if (readObject instanceof KeyPair) { KeyPair keyPair = (KeyPair)readObject; return keyPair.getPublic(); } else if (readObject instanceof PublicKey) { return (PublicKey)readObject; } else { return null; } } catch (Exception e) { throw new Exception("Cannot read public key", e); } }
Example 8
Source File: JsonWebKey.java From swim with Apache License 2.0 | 5 votes |
private static ECParameterSpec createECParameterSpec(String stdName) { try { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC"); final ECGenParameterSpec parameterSpec = new ECGenParameterSpec(stdName); keyPairGenerator.initialize(parameterSpec); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic(); return publicKey.getParams(); } catch (GeneralSecurityException cause) { throw new RuntimeException(cause); } }
Example 9
Source File: TestHDDSKeyGenerator.java From hadoop-ozone with Apache License 2.0 | 5 votes |
/** * In this test we assert that size that we specified is used for Key * generation. * @throws NoSuchProviderException - On Error, due to missing Java * dependencies. * @throws NoSuchAlgorithmException - On Error, due to missing Java * dependencies. */ @Test public void testGenerateKeyWithSize() throws NoSuchProviderException, NoSuchAlgorithmException { HDDSKeyGenerator keyGen = new HDDSKeyGenerator(config.getConfiguration()); KeyPair keyPair = keyGen.generateKey(4096); PublicKey publicKey = keyPair.getPublic(); if(publicKey instanceof RSAPublicKey) { Assert.assertEquals(4096, ((RSAPublicKey)(publicKey)).getModulus().bitLength()); } }
Example 10
Source File: JWTTokenGenerator.java From micro-integrator with Apache License 2.0 | 5 votes |
/** * Builds RSAKey using key store. * * @param jwtTokenDTO token info object * @param keyPairGenerator key pair generator * @return RSAKey built RSA Key which can be used to sign * @throws Exception */ private RSAKey generateRSAKeyWithKeyStore(JWTTokenInfoDTO jwtTokenDTO, KeyPairGenerator keyPairGenerator) throws Exception { KeyStore keystore = KeyStoreManager.getInstance(AppDeployerUtils.getTenantId()).getPrimaryKeyStore(); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAKey.Builder builder = new RSAKey.Builder(publicKey) .privateKey(privateKey).keyStore(keystore); return builder.keyID(jwtTokenDTO.getToken()).build(); }
Example 11
Source File: DHKeyExchange.java From openjsse with GNU General Public License v2.0 | 5 votes |
DHEPossession(int keyLength, SecureRandom random) { DHParameterSpec params = PredefinedDHParameterSpecs.definedParams.get(keyLength); try { KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("DiffieHellman"); if (params != null) { kpg.initialize(params, random); } else { kpg.initialize(keyLength, random); } KeyPair kp = generateDHKeyPair(kpg); if (kp == null) { throw new RuntimeException( "Could not generate DH keypair of " + keyLength + " bits"); } privateKey = kp.getPrivate(); publicKey = (DHPublicKey)kp.getPublic(); } catch (GeneralSecurityException gse) { throw new RuntimeException( "Could not generate DH keypair", gse); } this.namedGroup = NamedGroup.valueOf(publicKey.getParams()); }
Example 12
Source File: RsaUtil.java From base-admin with MIT License | 5 votes |
/** * 生成密钥对(公钥和私钥) */ private static Map<String, Object> genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(INITIALIZE_LENGTH); 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; }
Example 13
Source File: RSACoder.java From wecube-platform with Apache License 2.0 | 5 votes |
private AsymmetricKeyPair doInitKey() throws NoSuchAlgorithmException, UnsupportedEncodingException { initProvider(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(KEY_SIZE); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); AsymmetricKeyPair aKeyPair = AsymmetricKeyPairBuilder .withPublicKey(StringUtilsEx.encodeBase64String((publicKey.getEncoded()))) .withPrivateKey(StringUtilsEx.encodeBase64String(privateKey.getEncoded())).build(); return aKeyPair; }
Example 14
Source File: CertificateHelper.java From CapturePacket with MIT License | 4 votes |
public static KeyStore createRootCertificate(Authority authority, String keyStoreType) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, OperatorCreationException, CertificateException, KeyStoreException { KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, authority.commonName()); nameBuilder.addRDN(BCStyle.O, authority.organization()); nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName()); X500Name issuer = nameBuilder.build(); BigInteger serial = BigInteger.valueOf(initRandomSerial()); X500Name subject = issuer; PublicKey pubKey = keyPair.getPublic(); X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder( issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey); generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey)); generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign); generator.addExtension(Extension.keyUsage, false, usage); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); X509Certificate cert = signCertificate(generator, keyPair.getPrivate()); KeyStore result = KeyStore .getInstance(keyStoreType/* , PROVIDER_NAME */); result.load(null, null); result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), new Certificate[] { cert }); return result; }
Example 15
Source File: BouncyCastleSecurityProviderTool.java From CapturePacket with MIT License | 4 votes |
@Override public CertificateAndKey createCARootCertificate(CertificateInfo certificateInfo, KeyPair keyPair, String messageDigest) { if (certificateInfo.getNotBefore() == null) { throw new IllegalArgumentException("Must specify Not Before for server certificate"); } if (certificateInfo.getNotAfter() == null) { throw new IllegalArgumentException("Must specify Not After for server certificate"); } // create the X500Name that will be both the issuer and the subject of the new root certificate X500Name issuer = createX500NameForCertificate(certificateInfo); BigInteger serial = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE); PublicKey rootCertificatePublicKey = keyPair.getPublic(); String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, keyPair.getPrivate()); // this is a CA root certificate, so it is self-signed ContentSigner selfSigner = getCertificateSigner(keyPair.getPrivate(), signatureAlgorithm); ASN1EncodableVector extendedKeyUsages = new ASN1EncodableVector(); extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth); extendedKeyUsages.add(KeyPurposeId.anyExtendedKeyUsage); X509CertificateHolder certificateHolder; try { certificateHolder = new JcaX509v3CertificateBuilder( issuer, serial, certificateInfo.getNotBefore(), certificateInfo.getNotAfter(), issuer, rootCertificatePublicKey) .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(rootCertificatePublicKey)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.keyUsage, false, new KeyUsage( KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign)) .addExtension(Extension.extendedKeyUsage, false, new DERSequence(extendedKeyUsages)) .build(selfSigner); } catch (CertIOException e) { throw new CertificateCreationException("Error creating root certificate", e); } // convert the Bouncy Castle X590CertificateHolder to a JCA cert X509Certificate cert = convertToJcaCertificate(certificateHolder); return new CertificateAndKey(cert, keyPair.getPrivate()); }
Example 16
Source File: PKCS10AttrEncoding.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { // initializations int len = ids.length; Object[] values = { new ObjectIdentifier("1.2.3.4"), new GregorianCalendar(1970, 1, 25, 8, 56, 7).getTime(), "challenging" }; for (int j = 0; j < len; j++) { constructedMap.put(ids[j], values[j]); } X500Name subject = new X500Name("cn=Test"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); String sigAlg = "DSA"; keyGen.initialize(512); KeyPair pair = keyGen.generateKeyPair(); X509Key publicKey = (X509Key) pair.getPublic(); PrivateKey privateKey = pair.getPrivate(); Signature signature = Signature.getInstance(sigAlg); signature.initSign(privateKey); // Create the PKCS10 request PKCS10Attribute[] attrs = new PKCS10Attribute[len]; for (int j = 0; j < len; j++) { attrs[j] = new PKCS10Attribute(ids[j], values[j]); } PKCS10 req = new PKCS10(publicKey, new PKCS10Attributes(attrs)); System.out.println("List of attributes in constructed PKCS10 " + "request: "); checkAttributes(req.getAttributes().getElements()); // Encode the PKCS10 request and generate another PKCS10 request from // the encoded byte array req.encodeAndSign(subject, signature); PKCS10 resp = new PKCS10(req.getEncoded()); System.out.println("List of attributes in DER encoded PKCS10 Request:"); checkAttributes(resp.getAttributes().getElements()); if (failedCount > 0) { throw new RuntimeException("Attributes Compared : Failed"); } System.out.println("Attributes Compared : Pass"); }
Example 17
Source File: CertificateHelper.java From PowerTunnel with MIT License | 4 votes |
public static KeyStore createRootCertificate(Authority authority, String keyStoreType) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, OperatorCreationException, CertificateException, KeyStoreException { KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, authority.commonName()); nameBuilder.addRDN(BCStyle.O, authority.organization()); nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName()); X500Name issuer = nameBuilder.build(); BigInteger serial = BigInteger.valueOf(initRandomSerial()); X500Name subject = issuer; PublicKey pubKey = keyPair.getPublic(); X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder( issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey); generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey)); generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign); generator.addExtension(Extension.keyUsage, false, usage); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); X509Certificate cert = signCertificate(generator, keyPair.getPrivate()); KeyStore result = KeyStore .getInstance(keyStoreType/* , PROVIDER_NAME */); result.load(null, null); result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), new Certificate[] { cert }); return result; }
Example 18
Source File: TestOAEPPadding.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
public static void main(String args[]) throws Exception { cp = Security.getProvider("SunJCE"); System.out.println("Testing provider " + cp.getName() + "..."); Provider kfp = Security.getProvider("SunRsaSign"); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", kfp); kpg.initialize(2048); KeyPair kp = kpg.generateKeyPair(); privateKey = (RSAPrivateKey)kp.getPrivate(); publicKey = (RSAPublicKey)kp.getPublic(); // Test using a spec with each digest algorithm case // MD5 test(new OAEPParameterSpec("MD5", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("MD5", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("MD5", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("MD5", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("MD5", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT)); // SHA1 test(new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT)); // For default OAEPParameterSpec case (SHA1) test(null); // SHA-224 test(new OAEPParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT)); // SHA-256 test(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT)); // SHA-384 test(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT)); // SHA-512 test(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA224, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT)); test(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT)); if (failed) { throw new Exception("Test failed"); } }
Example 19
Source File: PKCS10AttrEncoding.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { // initializations int len = ids.length; Object[] values = { new ObjectIdentifier("1.2.3.4"), new GregorianCalendar(1970, 1, 25, 8, 56, 7).getTime(), "challenging" }; for (int j = 0; j < len; j++) { constructedMap.put(ids[j], values[j]); } X500Name subject = new X500Name("cn=Test"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); String sigAlg = "DSA"; keyGen.initialize(512); KeyPair pair = keyGen.generateKeyPair(); X509Key publicKey = (X509Key) pair.getPublic(); PrivateKey privateKey = pair.getPrivate(); Signature signature = Signature.getInstance(sigAlg); signature.initSign(privateKey); // Create the PKCS10 request PKCS10Attribute[] attrs = new PKCS10Attribute[len]; for (int j = 0; j < len; j++) { attrs[j] = new PKCS10Attribute(ids[j], values[j]); } PKCS10 req = new PKCS10(publicKey, new PKCS10Attributes(attrs)); System.out.println("List of attributes in constructed PKCS10 " + "request: "); checkAttributes(req.getAttributes().getElements()); // Encode the PKCS10 request and generate another PKCS10 request from // the encoded byte array req.encodeAndSign(subject, signature); PKCS10 resp = new PKCS10(req.getEncoded()); System.out.println("List of attributes in DER encoded PKCS10 Request:"); checkAttributes(resp.getAttributes().getElements()); if (failedCount > 0) { throw new RuntimeException("Attributes Compared : Failed"); } System.out.println("Attributes Compared : Pass"); }
Example 20
Source File: KeySizeTest.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { int iKeyPairSize = Integer.parseInt(args[0]); int maxLoopCnt = Integer.parseInt(args[1]); int failCount = 0; KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME); keyPairGen.initialize(iKeyPairSize); // Generate RSA keypair KeyPair keyPair = keyPairGen.generateKeyPair(); // Get priavte and public keys PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); try { if (!sizeTest(keyPair)) { failCount++; } } catch (Exception ex) { ex.printStackTrace(System.err); failCount++; } for (int iCnt = 0; iCnt < maxLoopCnt; iCnt++) { // Get keysize (modulus) of keys KeyFactory keyFact = KeyFactory.getInstance(KEYALG, PROVIDER_NAME); // Comparing binary length. RSAPrivateKeySpec privateKeySpec = (RSAPrivateKeySpec) keyFact.getKeySpec(privateKey, RSAPrivateKeySpec.class); int iPrivateKeySize = privateKeySpec.getModulus().bitLength(); RSAPublicKeySpec publicKeySpec = (RSAPublicKeySpec) keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class); int iPublicKeySize = publicKeySpec.getModulus().bitLength(); if ((iKeyPairSize != iPublicKeySize) || (iKeyPairSize != iPrivateKeySize)) { System.err.println("iKeyPairSize : " + iKeyPairSize); System.err.println("Generated a " + iPrivateKeySize + " bit RSA private key"); System.err.println("Generated a " + iPublicKeySize + " bit RSA public key"); failCount++; } } if (failCount > 0) { throw new RuntimeException("There are " + failCount + " tests failed."); } }