List of usage examples for java.security.spec RSAPublicKeySpec RSAPublicKeySpec
public RSAPublicKeySpec(BigInteger modulus, BigInteger publicExponent)
From source file:jenkins.security.RSAConfidentialKey.java
/** * Obtains the private key (lazily.)/*from w ww . j a v a 2s .c om*/ * <p> * This method is not publicly exposed as per the design principle of {@link ConfidentialKey}. * Instead of exposing private key, define methods that use them in specific way, such as * {@link RSADigitalSignatureConfidentialKey}. * * @throws Error * If key cannot be loaded for some reasons, we fail. */ protected synchronized RSAPrivateKey getPrivateKey() { try { if (priv == null) { byte[] payload = load(); if (payload == null) { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(2048, new SecureRandom()); // going beyond 2048 requires crypto extension KeyPair keys = gen.generateKeyPair(); priv = (RSAPrivateKey) keys.getPrivate(); pub = (RSAPublicKey) keys.getPublic(); store(priv.getEncoded()); } else { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); priv = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(payload)); RSAPrivateCrtKey pks = (RSAPrivateCrtKey) priv; pub = (RSAPublicKey) keyFactory .generatePublic(new RSAPublicKeySpec(pks.getModulus(), pks.getPublicExponent())); } } return priv; } catch (IOException e) { throw new Error("Failed to load the key: " + getId(), e); } catch (GeneralSecurityException e) { throw new Error("Failed to load the key: " + getId(), e); } }
From source file:com.github.aynu.mosir.core.standard.util.SecurityHelper.java
/** * RSA???/* w ww . j a va 2 s . c o m*/ * <dl> * <dt>? * <dd>RSA????????????? * </dl> * @param modulus * @param exponent ?? * @return RSA? */ public static RSAPublicKey createPublicKey(final BigInteger modulus, final BigInteger exponent) { try { final KeyFactory keyFactory = KeyFactory.getInstance(ALGO_KEY); return (RSAPublicKey) keyFactory.generatePublic(new RSAPublicKeySpec(modulus, exponent)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new StandardRuntimeException(e); } }
From source file:de.alpharogroup.crypto.key.PrivateKeyExtensions.java
/** * Generate the corresponding {@link PublicKey} object from the given {@link PrivateKey} object. * * @param privateKey/* www . jav a 2 s .c om*/ * the private key * @return the corresponding {@link PublicKey} object or null if generation failed. * @throws NoSuchAlgorithmException * the no such algorithm exception * @throws InvalidKeySpecException * the invalid key spec exception */ public static PublicKey generatePublicKey(final PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException { if (privateKey instanceof RSAPrivateKey) { final RSAPrivateCrtKey privk = (RSAPrivateCrtKey) privateKey; final RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(privk.getModulus(), privk.getPublicExponent()); final KeyFactory keyFactory = KeyFactory.getInstance(KeyPairGeneratorAlgorithm.RSA.getAlgorithm()); final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); return publicKey; } return null; }
From source file:ch.cyberduck.core.aquaticprime.DictionaryLicense.java
protected void verify(final NSDictionary dictionary, final String publicKey) throws InvalidLicenseException { if (null == dictionary) { throw new InvalidLicenseException(); }//from w w w . jav a 2 s . c om final NSData signature = (NSData) dictionary.objectForKey("Signature"); if (null == signature) { log.warn(String.format("Missing key 'Signature' in dictionary %s", dictionary)); throw new InvalidLicenseException(); } // Append all values StringBuilder values = new StringBuilder(); final ArrayList<String> keys = new ArrayList<>(dictionary.keySet()); // Sort lexicographically by key Collections.sort(keys, new NaturalOrderComparator()); for (String key : keys) { if ("Signature".equals(key)) { continue; } values.append(dictionary.objectForKey(key).toString()); } byte[] signaturebytes = signature.bytes(); byte[] plainbytes = values.toString().getBytes(Charset.forName("UTF-8")); try { final BigInteger modulus = new BigInteger(StringUtils.removeStart(publicKey, "0x"), 16); final BigInteger exponent = new BigInteger(Base64.decodeBase64("Aw==")); final KeySpec spec = new RSAPublicKeySpec(modulus, exponent); final PublicKey rsa = KeyFactory.getInstance("RSA").generatePublic(spec); final Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.DECRYPT_MODE, rsa); final MessageDigest sha1Digest = MessageDigest.getInstance("SHA1"); if (!Arrays.equals(rsaCipher.doFinal(signaturebytes), sha1Digest.digest(plainbytes))) { throw new InvalidLicenseException(); } } catch (NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException e) { log.warn(String.format("Signature verification failure for key %s", file)); throw new InvalidLicenseException(); } if (log.isInfoEnabled()) { log.info(String.format("Valid key in %s", file)); } }
From source file:ch.cyberduck.core.aquaticprime.DonationKey.java
/** * @return True if valid license key//from ww w. jav a 2s . c om */ @Override public boolean verify() { if (null == dictionary) { return false; } final NSData signature = (NSData) dictionary.objectForKey("Signature"); if (null == signature) { log.warn(String.format("Missing key 'Signature' in dictionary %s", dictionary)); return false; } // Append all values StringBuilder values = new StringBuilder(); final ArrayList<String> keys = new ArrayList<>(dictionary.keySet()); // Sort lexicographically by key Collections.sort(keys, new NaturalOrderComparator()); for (String key : keys) { if ("Signature".equals(key)) { continue; } values.append(dictionary.objectForKey(key).toString()); } byte[] signaturebytes = signature.bytes(); byte[] plainbytes = values.toString().getBytes(Charset.forName("UTF-8")); final boolean valid; try { final BigInteger modulus = new BigInteger(StringUtils.removeStart(this.getPublicKey(), "0x"), 16); final BigInteger exponent = new BigInteger(Base64.decodeBase64("Aw==")); final KeySpec spec = new RSAPublicKeySpec(modulus, exponent); final PublicKey rsa = KeyFactory.getInstance("RSA").generatePublic(spec); final Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.DECRYPT_MODE, rsa); final MessageDigest sha1Digest = MessageDigest.getInstance("SHA1"); valid = Arrays.equals(rsaCipher.doFinal(signaturebytes), sha1Digest.digest(plainbytes)); } catch (NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException e) { log.warn(String.format("Signature verification failure for key %s", file)); return false; } if (valid) { if (log.isInfoEnabled()) { log.info(String.format("Valid key in %s", file)); } } else { log.warn(String.format("Not a valid key in %s", file)); } return valid; }
From source file:com.tasktop.c2c.server.internal.profile.crypto.Rfc4716PublicKeyReader.java
/** * read a public key from the given text * /* w w w.j av a 2s .c om*/ * @param keySpec * the key specification. * @return the key or null if no key was found */ public SshPublicKey readPublicKey(String keySpec) { BufferedReader reader = new BufferedReader(new StringReader(keySpec)); String line; SshPublicKey key = null; boolean endFound = false; boolean dataStarted = false; boolean continueHeader = false; String base64Data = ""; try { while ((line = reader.readLine()) != null) { line = line.trim(); // skip blank lines. They shouldn't really be in there, but if they are we can ignore them. if (line.length() != 0) { if (key == null) { if (line.equals(START_MARKER)) { key = new SshPublicKey(); } } else { if (line.equals(END_MARKER)) { endFound = true; break; } else if (!dataStarted && (continueHeader || HEADER_PATTERN.matcher(line).matches())) { // skip headers continueHeader = line.endsWith("\""); } else { dataStarted = true; base64Data += line; } } } } if (!endFound) { key = null; } else { if (base64Data.length() > 0) { byte[] keyData = Base64.decodeBase64(StringUtils.getBytesUtf8(base64Data)); Rfc4253Reader keyReader = new Rfc4253Reader(keyData, 0); String algorithm = keyReader.readString(); if ("ssh-rsa".equals(algorithm)) { key.setAlgorithm("RSA"); BigInteger exponent = keyReader.readMpint(); BigInteger modulus = keyReader.readMpint(); try { KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm()); RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent); PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec); byte[] encoded = publicKey.getEncoded(); key.setKeyData(encoded); } catch (InvalidKeySpecException t) { getLogger().warn("Invalid key spec: " + t.getMessage(), t); } catch (NoSuchAlgorithmException t) { getLogger().warn("Invalid algorithm: " + t.getMessage(), t); } } } } } catch (IOException e) { throw new IllegalStateException(e); } if (key == null || key.getAlgorithm() == null || key.getKeyData() == null) { key = null; } return key; }
From source file:org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKey.java
public static PublicKey getRsaPublicKey(JsonWebKey key) { final Base64 decoder = new Base64(true); String e = (String) key.getKeyProperties().get("e"); String n = (String) key.getKeyProperties().get("n"); BigInteger modulus = new BigInteger(1, decoder.decode(n.getBytes(StandardCharsets.UTF_8))); BigInteger exponent = new BigInteger(1, decoder.decode(e.getBytes(StandardCharsets.UTF_8))); try {/*from w w w .j av a 2 s . c om*/ return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, exponent)); } catch (InvalidKeySpecException | NoSuchAlgorithmException e1) { throw new IllegalStateException(e1); } }
From source file:org.picketbox.json.key.RSAKey.java
/** * Convert to the JDK representation of a RSA Public Key * * @return// www. ja v a2 s . c o m * @throws ProcessingException */ public RSAPublicKey convertToPublicKey() throws ProcessingException { BigInteger bigModulus = new BigInteger(1, massage(Base64.decode(mod))); BigInteger bigEx = new BigInteger(1, massage(Base64.decode(exp))); try { KeyFactory rsaKeyFactory = KeyFactory.getInstance("rsa"); RSAPublicKeySpec kspec = new RSAPublicKeySpec(bigModulus, bigEx); return (RSAPublicKey) rsaKeyFactory.generatePublic(kspec); } catch (Exception e) { throw PicketBoxJSONMessages.MESSAGES.processingException(e); } }
From source file:com.cliqset.magicsig.MagicKey.java
public PublicKey getPublicKey() { try {//from ww w.j a va2 s .c om return KeyFactory.getInstance("RSA") .generatePublic(new RSAPublicKeySpec(new BigInteger(1, getN()), new BigInteger(1, getE()))); } catch (NoSuchAlgorithmException e) { return null; } catch (InvalidKeySpecException ex) { return null; } }
From source file:com.dreamworks.dsp.server.EmbeddedSftpServer.java
private PublicKey decodePublicKey() throws Exception { InputStream stream = new ClassPathResource("keys/sftp_rsa.pub").getInputStream(); byte[] decodeBuffer = Base64.decodeBase64(StreamUtils.copyToByteArray(stream)); ByteBuffer bb = ByteBuffer.wrap(decodeBuffer); int len = bb.getInt(); byte[] type = new byte[len]; bb.get(type);/* w w w. j a v a2 s .c o m*/ if ("ssh-rsa".equals(new String(type))) { BigInteger e = decodeBigInt(bb); BigInteger m = decodeBigInt(bb); RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e); return KeyFactory.getInstance("RSA").generatePublic(spec); } else { throw new IllegalArgumentException("Only supports RSA"); } }