java.security.KeyFactory Java Examples
The following examples show how to use
java.security.KeyFactory.
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: Encryption.java From Wurst7 with GNU General Public License v3.0 | 7 votes |
private KeyPair loadRsaKeys(Path publicFile, Path privateFile) throws GeneralSecurityException, ReflectiveOperationException, IOException { KeyFactory factory = KeyFactory.getInstance("RSA"); // load public key PublicKey publicKey; try(ObjectInputStream in = new ObjectInputStream(Files.newInputStream(publicFile))) { publicKey = factory.generatePublic(new RSAPublicKeySpec( (BigInteger)in.readObject(), (BigInteger)in.readObject())); } // load private key PrivateKey privateKey; try(ObjectInputStream in = new ObjectInputStream(Files.newInputStream(privateFile))) { privateKey = factory.generatePrivate(new RSAPrivateKeySpec( (BigInteger)in.readObject(), (BigInteger)in.readObject())); } return new KeyPair(publicKey, privateKey); }
Example #2
Source File: ECKeyTest.java From azure-keyvault-java with MIT License | 6 votes |
@BeforeClass public static void setUpBeforeClass() throws Exception { setProvider(Security.getProvider("SunEC")); EC_KEY_GENERATOR = KeyPairGenerator.getInstance("EC", _provider); Path byte_location = Paths.get("src/test/java/com/microsoft/azure/keyvault/cryptography/test/resources/byte_array.bin"); CEK = Files.readAllBytes(byte_location); FACTORY = KeyFactory.getInstance("EC", _provider); DIGEST_256 = MessageDigest.getInstance("SHA-256"); DIGEST_384 = MessageDigest.getInstance("SHA-384"); DIGEST_512 = MessageDigest.getInstance("SHA-512"); CURVE_TO_DIGEST = ImmutableMap.<JsonWebKeyCurveName, MessageDigest>builder() .put(JsonWebKeyCurveName.P_256, DIGEST_256) .put(JsonWebKeyCurveName.P_384, DIGEST_384) .put(JsonWebKeyCurveName.P_521, DIGEST_512) .put(JsonWebKeyCurveName.P_256K, DIGEST_256) .build(); //JsonWebKeyCurveName.SECP256K1) CURVE_LIST = Arrays.asList(JsonWebKeyCurveName.P_256, JsonWebKeyCurveName.P_384, JsonWebKeyCurveName.P_521, JsonWebKeyCurveName.P_256K); }
Example #3
Source File: FileBasedKeyResolver.java From cellery-security with Apache License 2.0 | 6 votes |
private void readPrivateKeyPKCS1PEM(String privateKeyPath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { String content = new String( Files.readAllBytes(Paths.get(privateKeyPath)), Charset.forName("UTF-8")); content = content.replaceAll("\\n", "").replace(START_RSA_PRIVATE_KEY, "") .replace(END_RSA_PRIVATE_KEY, ""); byte[] bytes = Base64.getDecoder().decode(content); DerInputStream derReader = new DerInputStream(bytes); DerValue[] seq = derReader.getSequence(0); // skip version seq[0]; BigInteger modulus = seq[1].getBigInteger(); BigInteger publicExp = seq[2].getBigInteger(); BigInteger privateExp = seq[3].getBigInteger(); BigInteger prime1 = seq[4].getBigInteger(); BigInteger prime2 = seq[5].getBigInteger(); BigInteger exp1 = seq[6].getBigInteger(); BigInteger exp2 = seq[7].getBigInteger(); BigInteger crtCoef = seq[8].getBigInteger(); RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); privateKey = keyFactory.generatePrivate(keySpec); }
Example #4
Source File: DHKeyExchange.java From openjsse with GNU General Public License v2.0 | 6 votes |
static DHECredentials valueOf(NamedGroup ng, byte[] encodedPublic) throws IOException, GeneralSecurityException { if (ng.type != NamedGroupType.NAMED_GROUP_FFDHE) { throw new RuntimeException( "Credentials decoding: Not FFDHE named group"); } if (encodedPublic == null || encodedPublic.length == 0) { return null; } DHParameterSpec params = (DHParameterSpec)ng.getParameterSpec(); if (params == null) { return null; } KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman"); DHPublicKeySpec spec = new DHPublicKeySpec( new BigInteger(1, encodedPublic), params.getP(), params.getG()); DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec); return new DHECredentials(publicKey, ng); }
Example #5
Source File: SignatureVerificationService.java From guardedbox with GNU Affero General Public License v3.0 | 6 votes |
/** * Verifies a signature. * * @param originalMessage The original message. * @param signedMessage The signature of the original message. * @param signingPublicKey The public key corresponding to the private key used to sign the message. * @return Boolean indicating if the signature is verified. */ public boolean verifySignature( byte[] originalMessage, byte[] signedMessage, byte[] signingPublicKey) { try { KeyFactory keyFactory = KeyFactory.getInstance(cryptographyProperties.getSignatureAlgorithm(), BouncyCastleProvider.PROVIDER_NAME); KeySpec keySpec = new X509EncodedKeySpec(new SubjectPublicKeyInfo(signatureAlgorithmId, signingPublicKey).getEncoded()); PublicKey pubKey = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(cryptographyProperties.getSignatureAlgorithm(), BouncyCastleProvider.PROVIDER_NAME); signature.initVerify(pubKey); signature.update(originalMessage); return signature.verify(signedMessage); } catch (NoSuchAlgorithmException | NoSuchProviderException | IOException | InvalidKeySpecException | InvalidKeyException | SignatureException e) { return false; } }
Example #6
Source File: GooglePlayAPI.java From raccoon4 with Apache License 2.0 | 6 votes |
public static PublicKey createKeyFromString(String str, byte[] bArr) { try { byte[] decode = Base64.decode(str, 0); int readInt = readInt(decode, 0); byte[] obj = new byte[readInt]; System.arraycopy(decode, 4, obj, 0, readInt); BigInteger bigInteger = new BigInteger(1, obj); int readInt2 = readInt(decode, readInt + 4); byte[] obj2 = new byte[readInt2]; System.arraycopy(decode, readInt + 8, obj2, 0, readInt2); BigInteger bigInteger2 = new BigInteger(1, obj2); decode = MessageDigest.getInstance("SHA-1").digest(decode); bArr[0] = (byte) 0; System.arraycopy(decode, 0, bArr, 1, 4); return KeyFactory.getInstance("RSA").generatePublic( new RSAPublicKeySpec(bigInteger, bigInteger2)); } catch (Throwable e) { throw new RuntimeException(e); } }
Example #7
Source File: BasicChecker.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
/** * Internal method to create a new key with inherited key parameters. * * @param keyValueKey key from which to obtain key value * @param keyParamsKey key from which to obtain key parameters * @return new public key having value and parameters * @throws CertPathValidatorException if keys are not appropriate types * for this operation */ static PublicKey makeInheritedParamsKey(PublicKey keyValueKey, PublicKey keyParamsKey) throws CertPathValidatorException { if (!(keyValueKey instanceof DSAPublicKey) || !(keyParamsKey instanceof DSAPublicKey)) throw new CertPathValidatorException("Input key is not " + "appropriate type for " + "inheriting parameters"); DSAParams params = ((DSAPublicKey)keyParamsKey).getParams(); if (params == null) throw new CertPathValidatorException("Key parameters missing"); try { BigInteger y = ((DSAPublicKey)keyValueKey).getY(); KeyFactory kf = KeyFactory.getInstance("DSA"); DSAPublicKeySpec ks = new DSAPublicKeySpec(y, params.getP(), params.getQ(), params.getG()); return kf.generatePublic(ks); } catch (GeneralSecurityException e) { throw new CertPathValidatorException("Unable to generate key with" + " inherited parameters: " + e.getMessage(), e); } }
Example #8
Source File: BouncyCryptography.java From Jabit with Apache License 2.0 | 6 votes |
@Override public boolean isSignatureValid(byte[] data, byte[] signature, Pubkey pubkey) { try { ECParameterSpec spec = new ECParameterSpec( EC_CURVE_PARAMETERS.getCurve(), EC_CURVE_PARAMETERS.getG(), EC_CURVE_PARAMETERS.getN(), EC_CURVE_PARAMETERS.getH(), EC_CURVE_PARAMETERS.getSeed() ); ECPoint Q = keyToPoint(pubkey.getSigningKey()); KeySpec keySpec = new ECPublicKeySpec(Q, spec); PublicKey publicKey = KeyFactory.getInstance(ALGORITHM_ECDSA, provider).generatePublic(keySpec); Signature sig = Signature.getInstance(ALGORITHM_ECDSA, provider); sig.initVerify(publicKey); sig.update(data); return sig.verify(signature); } catch (GeneralSecurityException e) { throw new ApplicationException(e); } }
Example #9
Source File: KeyPairUtilTest.java From keystore-explorer with GNU General Public License v3.0 | 6 votes |
@Test public void testValidKeyPairWithDifferentAlgorithmNames() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, CryptoException, InvalidKeySpecException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA", BC); keyPairGenerator.initialize(new ECGenParameterSpec("prime256v1"), SecureRandom.getInstance("SHA1PRNG")); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // private key has algorithm "ECDSA" (because it was generated by BC) PrivateKey privateKey = keyPair.getPrivate(); // now convert public key to standard JCE object (so it has algorithm name "EC" instead of "ECDSA") PublicKey publicKey = KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(keyPair.getPublic().getEncoded())); assertTrue(KeyPairUtil.validKeyPair(privateKey, publicKey)); }
Example #10
Source File: Ssh2DsaPrivateKey.java From j2ssh-maverick with GNU Lesser General Public License v3.0 | 6 votes |
public Ssh2DsaPrivateKey(BigInteger p, BigInteger q, BigInteger g, BigInteger x, BigInteger y) throws SshException { try { KeyFactory kf = JCEProvider .getProviderForAlgorithm(JCEAlgorithms.JCE_DSA) == null ? KeyFactory .getInstance(JCEAlgorithms.JCE_DSA) : KeyFactory .getInstance(JCEAlgorithms.JCE_DSA, JCEProvider .getProviderForAlgorithm(JCEAlgorithms.JCE_DSA)); DSAPrivateKeySpec spec = new DSAPrivateKeySpec(x, p, q, g); prv = (DSAPrivateKey) kf.generatePrivate(spec); pub = new Ssh2DsaPublicKey(p, q, g, y); } catch (Throwable e) { throw new SshException(e); } }
Example #11
Source File: CipherHelper.java From flow-platform-x with Apache License 2.0 | 6 votes |
/** * from <type><space><base64data><space><comment> to public key */ private static PublicKey toPublicKey(String sshPublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { String[] line = sshPublicKey.trim().split(" ", 3); String type = line[0]; String content = line[1]; ByteBuffer buf = ByteBuffer.wrap(Base64.getDecoder().decode(content)); // format of decoded content is: <type><keyparams> // where type and each param is a DER string String decodedType = new String(readDERString(buf)); if (!decodedType.equals(type)) { throw new IllegalArgumentException("expected " + type + ", got " + decodedType); } if (type.equals("ssh-rsa")) { BigInteger e = new BigInteger(readDERString(buf)); BigInteger y = new BigInteger(readDERString(buf)); return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(y, e)); } throw new InvalidKeySpecException("Unknown key type '" + type + "'"); }
Example #12
Source File: JKS.java From fdroidclient with GNU General Public License v3.0 | 6 votes |
public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { alias = alias.toLowerCase(Locale.ENGLISH); if (!privateKeys.containsKey(alias)) return null; byte[] key = decryptKey((byte[]) privateKeys.get(alias), charsToBytes(password)); Certificate[] chain = engineGetCertificateChain(alias); if (chain.length > 0) { try { // Private and public keys MUST have the same algorithm. KeyFactory fact = KeyFactory.getInstance( chain[0].getPublicKey().getAlgorithm()); return fact.generatePrivate(new PKCS8EncodedKeySpec(key)); } catch (InvalidKeySpecException x) { throw new UnrecoverableKeyException(x.getMessage()); } } else return new SecretKeySpec(key, alias); }
Example #13
Source File: Ssh2EcdsaSha2NistPublicKey.java From j2ssh-maverick with GNU Lesser General Public License v3.0 | 6 votes |
public static void main(String[] args) throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC"); ECGenParameterSpec gps = new ECGenParameterSpec ("secp256r1"); // NIST P-256 kpg.initialize(gps); KeyPair apair = kpg.generateKeyPair(); ECPublicKey apub = (ECPublicKey)apair.getPublic(); ECParameterSpec aspec = apub.getParams(); // could serialize aspec for later use (in compatible JRE) // // for test only reuse bogus pubkey, for real substitute values ECPoint apoint = apub.getW(); BigInteger x = apoint.getAffineX(), y = apoint.getAffineY(); // construct point plus params to pubkey ECPoint bpoint = new ECPoint (x,y); ECPublicKeySpec bpubs = new ECPublicKeySpec (bpoint, aspec); KeyFactory kfa = KeyFactory.getInstance ("EC"); ECPublicKey bpub = (ECPublicKey) kfa.generatePublic(bpubs); new Ssh2EcdsaSha2NistPublicKey(bpub); }
Example #14
Source File: GenerateKeyImpl.java From julongchain with Apache License 2.0 | 6 votes |
public PrivateKey LoadPrivateKey(String path, String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // Read Private Key. File filePrivateKey = new File(path + "/private.key"); FileInputStream fis = new FileInputStream(path + "/private.key"); byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()]; fis.read(encodedPrivateKey); fis.close(); KeyFactory keyFactory = KeyFactory.getInstance(algorithm); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec( encodedPrivateKey); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return privateKey; }
Example #15
Source File: BasicChecker.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
/** * Internal method to create a new key with inherited key parameters. * * @param keyValueKey key from which to obtain key value * @param keyParamsKey key from which to obtain key parameters * @return new public key having value and parameters * @throws CertPathValidatorException if keys are not appropriate types * for this operation */ static PublicKey makeInheritedParamsKey(PublicKey keyValueKey, PublicKey keyParamsKey) throws CertPathValidatorException { if (!(keyValueKey instanceof DSAPublicKey) || !(keyParamsKey instanceof DSAPublicKey)) throw new CertPathValidatorException("Input key is not " + "appropriate type for " + "inheriting parameters"); DSAParams params = ((DSAPublicKey)keyParamsKey).getParams(); if (params == null) throw new CertPathValidatorException("Key parameters missing"); try { BigInteger y = ((DSAPublicKey)keyValueKey).getY(); KeyFactory kf = KeyFactory.getInstance("DSA"); DSAPublicKeySpec ks = new DSAPublicKeySpec(y, params.getP(), params.getQ(), params.getG()); return kf.generatePublic(ks); } catch (GeneralSecurityException e) { throw new CertPathValidatorException("Unable to generate key with" + " inherited parameters: " + e.getMessage(), e); } }
Example #16
Source File: MoviesMPJWTConfigurationProvider.java From tomee with Apache License 2.0 | 6 votes |
@Produces Optional<JWTAuthConfiguration> getOptionalContextInfo() throws NoSuchAlgorithmException, InvalidKeySpecException { final String pemEncoded = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlivFI8qB4D0y2jy0CfEq" + "Fyy46R0o7S8TKpsx5xbHKoU1VWg6QkQm+ntyIv1p4kE1sPEQO73+HY8+Bzs75XwR" + "TYL1BmR1w8J5hmjVWjc6R2BTBGAYRPFRhor3kpM6ni2SPmNNhurEAHw7TaqszP5e" + "UF/F9+KEBWkwVta+PZ37bwqSE4sCb1soZFrVz/UT/LF4tYpuVYt3YbqToZ3pZOZ9" + "AX2o1GCG3xwOjkc4x0W7ezbQZdC9iftPxVHR8irOijJRRjcPDtA6vPKpzLl6CyYn" + "sIYPd99ltwxTHjr3npfv/3Lw50bAkbT4HeLFxTx4flEoZLKO/g0bAoV2uqBhkA9x" + "nQIDAQAB"; byte[] encodedBytes = Base64.getDecoder().decode(pemEncoded); final X509EncodedKeySpec spec = new X509EncodedKeySpec(encodedBytes); final KeyFactory kf = KeyFactory.getInstance("RSA"); final RSAPublicKey pk = (RSAPublicKey) kf.generatePublic(spec); return Optional.of(JWTAuthConfiguration.authConfiguration(pk, "https://server.example.com", false)); }
Example #17
Source File: KeyCloakRsaKeyFetcher.java From sunbird-lms-service with MIT License | 6 votes |
/** * This method will accept keycloak base URL and realm name. Based on provided values it will * fetch public key from keycloak. * * @param url A string value having keycloak base URL * @param realm Keycloak realm name * @return Public key used to verify user access token. */ public PublicKey getPublicKeyFromKeyCloak(String url, String realm) { try { Map<String, String> valueMap = null; Decoder urlDecoder = Base64.getUrlDecoder(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); String publicKeyString = requestKeyFromKeycloak(url, realm); if (publicKeyString != null) { valueMap = getValuesFromJson(publicKeyString); if (valueMap != null) { BigInteger modulus = new BigInteger(1, urlDecoder.decode(valueMap.get(MODULUS))); BigInteger publicExponent = new BigInteger(1, urlDecoder.decode(valueMap.get(EXPONENT))); PublicKey key = keyFactory.generatePublic(new RSAPublicKeySpec(modulus, publicExponent)); saveToCache(key); return key; } } } catch (Exception e) { ProjectLogger.log( "KeyCloakRsaKeyFetcher:getPublicKeyFromKeyCloak: Exception occurred with message = " + e.getMessage(), LoggerEnum.ERROR); } return null; }
Example #18
Source File: ExportControlled.java From Komondor with GNU General Public License v3.0 | 6 votes |
public static RSAPublicKey decodeRSAPublicKey(String key, ExceptionInterceptor interceptor) throws SQLException { try { if (key == null) { throw new SQLException("key parameter is null"); } int offset = key.indexOf("\n") + 1; int len = key.indexOf("-----END PUBLIC KEY-----") - offset; // TODO: use standard decoders with Java 6+ byte[] certificateData = Base64Decoder.decode(key.getBytes(), offset, len); X509EncodedKeySpec spec = new X509EncodedKeySpec(certificateData); KeyFactory kf = KeyFactory.getInstance("RSA"); return (RSAPublicKey) kf.generatePublic(spec); } catch (Exception ex) { throw SQLError.createSQLException("Unable to decode public key", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, ex, interceptor); } }
Example #19
Source File: RsaCipherProvider.java From RxFingerprint with Apache License 2.0 | 6 votes |
@Override @TargetApi(Build.VERSION_CODES.M) Cipher cipherForEncryption() throws GeneralSecurityException, IOException { KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEY_STORE); keyGenerator.initialize(getKeyGenParameterSpecBuilder(keyName, KeyProperties.BLOCK_MODE_ECB, KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1, invalidatedByBiometricEnrollment) .build()); keyGenerator.generateKeyPair(); KeyFactory keyFactory = KeyFactory.getInstance(KeyProperties.KEY_ALGORITHM_RSA); Cipher cipher = createCipher(); cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(keyFactory, keyStore)); return cipher; }
Example #20
Source File: DKIMSign.java From james-project with Apache License 2.0 | 6 votes |
private PrivateKey extractPrivateKey(InputStream rawKey, char[] passphrase) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); try (InputStreamReader pemReader = new InputStreamReader(rawKey)) { try (PEMParser pemParser = new PEMParser(pemReader)) { Object pemObject = pemParser.readObject(); JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); KeyPair keyPair; if (pemObject instanceof PrivateKeyInfo) { return converter.getPrivateKey((PrivateKeyInfo)pemObject); } if (pemObject instanceof PEMEncryptedKeyPair) { PEMEncryptedKeyPair pemEncryptedKeyPair = (PEMEncryptedKeyPair) pemObject; PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase); keyPair = converter.getKeyPair(pemEncryptedKeyPair.decryptKeyPair(decProv)); } else { keyPair = converter.getKeyPair((PEMKeyPair) pemObject); } KeyFactory keyFac = KeyFactory.getInstance("RSA"); RSAPrivateCrtKeySpec privateKeySpec = keyFac.getKeySpec(keyPair.getPrivate(), RSAPrivateCrtKeySpec.class); return keyFac.generatePrivate(privateKeySpec); } } }
Example #21
Source File: ZhifubaoHelper.java From android-common-utils with Apache License 2.0 | 6 votes |
/** * 08-13 16:50:39.352: W/System.err(26987): * java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: * error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag * @param content * @param privateKey * @return */ public static String sign(String content, String privateKey) { try { PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey)); KeyFactory keyf; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){ keyf = KeyFactory.getInstance("RSA", "BC"); }else { keyf = KeyFactory.getInstance(ALGORITHM);//rsa } PrivateKey priKey = keyf.generatePrivate(priPKCS8); java.security.Signature signature = java.security.Signature .getInstance(SIGN_ALGORITHMS); signature.initSign(priKey); signature.update(content.getBytes(DEFAULT_CHARSET)); byte[] signed = signature.sign(); return Base64.encode(signed); } catch (Exception e) { e.printStackTrace(); } return null; }
Example #22
Source File: FakeBurpCertificateBuilder.java From SAMLRaider with MIT License | 6 votes |
@Override public void generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException { // https://github.com/bcgit/bc-java/blob/53d17ef99e30c6bd49e6eec9235e3eefca6a222d/pkix/src/test/java/org/bouncycastle/cert/test/CertTest.java RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger( "b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(new BigInteger( "b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger( "9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger( "c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger( "b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger( "b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); setPrivateKey(fact.generatePrivate(privKeySpec)); setPublicKey(fact.generatePublic(pubKeySpec)); }
Example #23
Source File: DNSSECWithBC.java From dnsjava with BSD 2-Clause "Simplified" License | 5 votes |
private static PublicKey toEdDSAPublicKey(byte[] key, ASN1ObjectIdentifier algId) throws GeneralSecurityException, IOException { // Key is encoded as plain octets, rfc8080#section-3 // wrap it in ASN.1 format so we can use X509EncodedKeySpec to read it as JCA SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(new AlgorithmIdentifier(algId), key); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyInfo.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("EdDSA"); return keyFactory.generatePublic(keySpec); }
Example #24
Source File: NewCertificateContract.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) { try { X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes()); AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm(); PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec); String algorithm = publicKey.getAlgorithm(); KeyFactory keyFact = KeyFactory.getInstance(algorithm); RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class); BigInteger modulus = keySpec.getModulus(); return modulus.toString(2).length(); } catch (Exception var9) { throw new IllegalArgumentException(var9); } }
Example #25
Source File: PrivateKeyEventDecryptor.java From xyz-hub with Apache License 2.0 | 5 votes |
/** * Try to create a RSA private key from a PKCS#8 PEM without header and footer. * * @param pkcs8Data The private key in PKCS#8 PEM format without header and footer. * @return Returns the {@link PrivateKey} or null if there was a problem. */ public static PrivateKey createPrivateKey(final String pkcs8Data) { try { KeyFactory keyFactory = KeyFactory.getInstance(RSA); return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(pkcs8Data.getBytes(UTF_8)))); } catch (Exception e) { logger.error("Could not create unencrypted private key from environment variable", e); return null; } }
Example #26
Source File: SecurityManagerTest.java From snowflake-ingest-java with Apache License 2.0 | 5 votes |
/** * Converts encodedBase64 publicKey back to the RSA scheme PublicKey object. * <p> * @param base64PublicKey * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ private PublicKey loadPublicKey(String base64PublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] data = Base64.getMimeDecoder().decode(base64PublicKey); X509EncodedKeySpec spec = new X509EncodedKeySpec(data); KeyFactory factory = KeyFactory.getInstance("RSA"); return factory.generatePublic(spec); }
Example #27
Source File: AuthorizationServerConfiguration.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
@Bean KeyPair keyPair() { try { String privateExponent = "3851612021791312596791631935569878540203393691253311342052463788814433805390794604753109719790052408607029530149004451377846406736413270923596916756321977922303381344613407820854322190592787335193581632323728135479679928871596911841005827348430783250026013354350760878678723915119966019947072651782000702927096735228356171563532131162414366310012554312756036441054404004920678199077822575051043273088621405687950081861819700809912238863867947415641838115425624808671834312114785499017269379478439158796130804789241476050832773822038351367878951389438751088021113551495469440016698505614123035099067172660197922333993"; String modulus = "18044398961479537755088511127417480155072543594514852056908450877656126120801808993616738273349107491806340290040410660515399239279742407357192875363433659810851147557504389760192273458065587503508596714389889971758652047927503525007076910925306186421971180013159326306810174367375596043267660331677530921991343349336096643043840224352451615452251387611820750171352353189973315443889352557807329336576421211370350554195530374360110583327093711721857129170040527236951522127488980970085401773781530555922385755722534685479501240842392531455355164896023070459024737908929308707435474197069199421373363801477026083786683"; String exponent = "65537"; RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(exponent)); RSAPrivateKeySpec privateSpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent)); KeyFactory factory = KeyFactory.getInstance("RSA"); return new KeyPair(factory.generatePublic(publicSpec), factory.generatePrivate(privateSpec)); } catch ( Exception e ) { throw new IllegalArgumentException(e); } }
Example #28
Source File: PluginSandboxPolicy.java From rapidminer-studio with GNU Affero General Public License v3.0 | 5 votes |
/** * Creates the public key based on the Base64 encoded key string. * * @param base64EncodedKey * the Base64 encoded public key * @return the key or {@code null} if creation failed */ private static PublicKey createPublicKey(final String base64EncodedKey) { try { KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM); X509EncodedKeySpec spec = new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(base64EncodedKey)); return factory.generatePublic(spec); } catch (GeneralSecurityException e) { // no log service available yet, so use syserr System.err.println("Failed to initialize public key to verify extension certificates!"); e.printStackTrace(); return null; } }
Example #29
Source File: KeyUtils.java From keycloak with Apache License 2.0 | 5 votes |
public static PrivateKey privateKeyFromString(String key) { try { KeyFactory kf = KeyFactory.getInstance("RSA"); byte[] encoded = Base64.getDecoder().decode(key); return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException(e); } }
Example #30
Source File: LicenseManager.java From boubei-tss with Apache License 2.0 | 5 votes |
/** * <pre> * 验证license是否合法:根据公钥验证签名是否合法。 * </pre> * @param license * @return * @throws Exception */ boolean validate(License license) throws Exception { File keyFile = new File(LicenseFactory.PUBLIC_KEY_FILE); String publicKey = FileHelper.readFile(keyFile).trim(); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(EasyUtils.decodeHex(publicKey)); KeyFactory keyFactory = KeyFactory.getInstance(LicenseFactory.KEY_ALGORITHM); java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); Signature sig = Signature.getInstance(LicenseFactory.KEY_ALGORITHM); sig.initVerify(pubKey); sig.update(license.getFingerprint()); return sig.verify(EasyUtils.decodeHex(license.signature)); }