List of usage examples for java.security KeyFactory generatePublic
public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException
From source file:org.bedework.util.security.pki.PKITools.java
/** * @param pubKeyBytes// ww w . j a v a2s . c om * @param item * @return encrypted value * @throws PKIException */ public String encrypt(final byte[] pubKeyBytes, final String item) throws PKIException { byte[] encryptedItem = null; Cipher asymmetricCipher; try { X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes); Key publicKey; if (curSchema.pName == null) { KeyFactory kf = KeyFactory.getInstance(curSchema.algorithm); publicKey = kf.generatePublic(publicKeySpec); asymmetricCipher = Cipher.getInstance(curSchema.algorithm); } else { KeyFactory kf = KeyFactory.getInstance(curSchema.algorithm, curSchema.pName); publicKey = kf.generatePublic(publicKeySpec); asymmetricCipher = Cipher.getInstance(curSchema.algorithm, curSchema.pName); } asymmetricCipher.init(Cipher.ENCRYPT_MODE, publicKey); encryptedItem = asymmetricCipher.doFinal(item.getBytes()); } catch (Throwable t) { throw new PKIException(t); } return new String(b64.encode(encryptedItem)); }
From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java
private void encryptAndWriteAESKey(SecretKey aeskey, File dest) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException { Cipher keyc;/* w ww . ja v a 2 s . co m*/ AssetManager am = getAssets(); InputStream in = am.open("mouflon_key.pub"); byte[] readFromFile = new byte[in.available()]; //TODO check that this is 294 bytes and replace with a constant. in.available is not guaranteed to return a useful value in.read(readFromFile); keyc = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); //ECB and CBC etc don't make sense for RSA, but the way this API is designed you have to specify something. KeyFactory kf = KeyFactory.getInstance("RSA"); KeySpec ks = new X509EncodedKeySpec(readFromFile); RSAPublicKey key = (RSAPublicKey) kf.generatePublic(ks); keyc.init(Cipher.ENCRYPT_MODE, key); //byte[] encrpytedKey = keyc.doFinal(aeskey.getEncoded()); FileOutputStream out = new FileOutputStream(dest); CipherOutputStream outcipher = new CipherOutputStream(out, keyc); outcipher.write(aeskey.getEncoded()); outcipher.close(); out.close(); }
From source file:be.e_contract.mycarenet.common.SessionKey.java
/** * Loader constructor. Loads an existing MyCareNet session key. * /*from ww w .j a v a 2 s . c o m*/ * @param encodedPrivateKey * @param encodedPublicKey * @param encodedCertificate * @param notBefore * @param notAfter */ public SessionKey(byte[] encodedPrivateKey, byte[] encodedPublicKey, byte[] encodedCertificate, Date notBefore, Date notAfter) { this.notBefore = notBefore; this.notAfter = notAfter; X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encodedPublicKey); KeyFactory keyFactory; try { keyFactory = KeyFactory.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("RSA", e); } PublicKey publicKey; try { publicKey = keyFactory.generatePublic(x509EncodedKeySpec); } catch (InvalidKeySpecException e) { throw new RuntimeException("invalid public key: " + e.getMessage(), e); } PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); PrivateKey privateKey; try { privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); } catch (InvalidKeySpecException e) { throw new RuntimeException("invalid private key: " + e.getMessage(), e); } this.keyPair = new KeyPair(publicKey, privateKey); CertificateFactory certificateFactory; try { certificateFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new RuntimeException(e); } try { this.certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(encodedCertificate)); } catch (CertificateException e) { throw new RuntimeException("certificate decoding error: " + e.getMessage(), e); } }
From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java
private DSAPublicKey decodeDsaPublicKeyFromBitString(DERBitString der, BigInteger p, BigInteger q, BigInteger g) throws SpkacException { try {/*from ww w . j a v a2 s .c o m*/ BigInteger y = ASN1Integer.getInstance(der.getBytes()).getValue(); KeyFactory keyFact = KeyFactory.getInstance("DSA"); return (DSAPublicKey) keyFact.generatePublic(new DSAPublicKeySpec(y, p, q, g)); } catch (GeneralSecurityException ex) { throw new SpkacException(res.getString("NoGenerateDsaPublicKeyFromSpkac.exception.message"), ex); } catch (Exception ex) { throw new SpkacException(res.getString("NoGenerateDsaPublicKeyFromSpkac.exception.message"), ex); } }
From source file:com.axelor.apps.account.service.payment.PayboxService.java
/** Chargement de la cle AU FORMAT pem * Alors ajouter la dpendance dans le fichier pom.xml : * <dependency>/*from ww w.jav a2 s. com*/ * <groupId>org.bouncycastle</groupId> * <artifactId>bcprov-jdk15on</artifactId> * <version>1.47</version> * </dependency> * * Ainsi que l'import : import org.bouncycastle.util.io.pem.PemReader; * * @param pubKeyFile * @return * @throws Exception */ private PublicKey getPubKey(String pubKeyPath) throws Exception { PemReader reader = new PemReader(new FileReader(pubKeyPath)); byte[] pubKey = reader.readPemObject().getContent(); reader.close(); KeyFactory keyFactory = KeyFactory.getInstance(this.ENCRYPTION_ALGORITHM); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKey); return keyFactory.generatePublic(pubKeySpec); }
From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java
private RSAPublicKey decodeRsaPublicKeyFromBitString(DERBitString der) throws SpkacException { try {/*from w w w . j ava2 s . c o m*/ ASN1Sequence rsaPublicKey = ASN1Sequence.getInstance(der.getBytes()); BigInteger modulus = ((ASN1Integer) rsaPublicKey.getObjectAt(0)).getValue(); BigInteger publicExponent = ((ASN1Integer) rsaPublicKey.getObjectAt(1)).getValue(); KeyFactory keyFact = KeyFactory.getInstance("RSA"); return (RSAPublicKey) keyFact.generatePublic(new RSAPublicKeySpec(modulus, publicExponent)); } catch (GeneralSecurityException ex) { throw new SpkacException(res.getString("NoGenerateRsaPublicKeyFromSpkac.exception.message"), ex); } catch (Exception ex) { throw new SpkacException(res.getString("NoGenerateRsaPublicKeyFromSpkac.exception.message"), ex); } }
From source file:com.thoughtworks.go.server.util.HttpTestUtil.java
private KeyPair generateKeyPair() { try {/* w w w.j av a2 s. com*/ KeyPair seed = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair(); RSAPrivateKey privateSeed = (RSAPrivateKey) seed.getPrivate(); RSAPublicKey publicSeed = (RSAPublicKey) seed.getPublic(); KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateSeed.getModulus(), privateSeed.getPrivateExponent()); RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(publicSeed.getModulus(), publicSeed.getPublicExponent()); return new KeyPair(fact.generatePublic(publicKeySpec), fact.generatePrivate(privateKeySpec)); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.axelor.apps.account.service.payment.PayboxService.java
/** Chargement de la cle AU FORMAT der * Utliser la commande suivante pour 'convertir' la cl 'pem' en 'der' * openssl rsa -inform PEM -in pubkey.pem -outform DER -pubin -out pubkey.der */*from w w w. j av a2 s .c o m*/ * @param pubKeyFile * @return * @throws Exception */ @Deprecated private PublicKey getPubKeyDer(String pubKeyPath) throws Exception { FileInputStream fis = new FileInputStream(pubKeyPath); DataInputStream dis = new DataInputStream(fis); byte[] pubKeyBytes = new byte[fis.available()]; dis.readFully(pubKeyBytes); fis.close(); dis.close(); KeyFactory keyFactory = KeyFactory.getInstance(this.ENCRYPTION_ALGORITHM); // extraction cle X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes); return keyFactory.generatePublic(pubSpec); }
From source file:net.padlocksoftware.padlock.validator.Validator.java
private PublicKey convertPublicKey(String publicKey, boolean isRSA) { PublicKey pub = null;// ww w . j a v a 2s . co m try { byte[] pubKey = Hex.decodeHex(publicKey.toCharArray()); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKey); KeyFactory keyFactory = KeyFactory.getInstance(isRSA ? "RSA" : "DSA"); if (isRSA) { pub = (RSAPublicKey) keyFactory.generatePublic(pubSpec); } else { pub = (DSAPublicKey) keyFactory.generatePublic(pubSpec); } } catch (InvalidKeySpecException ex) { logger.log(Level.FINE, null, ex); } catch (NoSuchAlgorithmException ex) { logger.log(Level.FINE, null, ex); } catch (DecoderException ex) { logger.log(Level.FINE, null, ex); } catch (ClassCastException ex) { logger.log(Level.FINE, null, ex); } return pub; }
From source file:com.squid.kraken.v4.api.core.customer.AuthServiceImpl.java
public AccessToken getTokenFromJWT(AppContext ctx, String jwt) { try {/*from ww w .j a v a2s . c o m*/ // first pass to read the issuer (client Id) JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder().setSkipAllValidators() .setDisableRequireSignature().setSkipSignatureVerification().build(); JwtContext jwtContext = firstPassJwtConsumer.process(jwt); JwtClaims claims = jwtContext.getJwtClaims(); String issuer = claims.getIssuer(); String customerId = claims.getStringClaimValue("customerId"); ClientPK clientId = new ClientPK(claims.getStringClaimValue("customerId"), issuer); // load the client using superuser to get the key AppContext rootUserContext = ServiceUtils.getInstance().getRootUserContext(customerId); Client client = DAOFactory.getDAOFactory().getDAO(Client.class).readNotNull(rootUserContext, clientId); String publicKeyPEM = client.getJWTKeyPublic(); publicKeyPEM = publicKeyPEM.substring(publicKeyPEM.indexOf('\n'), publicKeyPEM.lastIndexOf('\n')); publicKeyPEM = publicKeyPEM.replace("\n", ""); byte[] publicKey = Base64.decodeBase64(publicKeyPEM); KeySpec keySpec = new X509EncodedKeySpec(publicKey); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey key = kf.generatePublic(keySpec); JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime() // the JWT must have an expiration time .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew .setRequireSubject() // the JWT must have a subject claim .setVerificationKey(key) // verify the signature with the public key .build(); // create the JwtConsumer instance // validate the JWT jwtConsumer.processContext(jwtContext); // create the token String userId = jwtContext.getJwtClaims().getSubject(); AccessToken token = ServiceUtils.getInstance().createToken(customerId, clientId, userId, System.currentTimeMillis(), ServiceUtils.getInstance().getTokenExpirationPeriodMillis(), null, null); return token; } catch (MalformedClaimException e) { logger.debug(e.getMessage()); throw new InvalidCredentialsAPIException("Invalid JWT Claim", ctx.isNoError()); } catch (InvalidJwtException e) { logger.debug(e.getMessage()); throw new InvalidCredentialsAPIException("Invalid JWT", ctx.isNoError()); } catch (NoSuchAlgorithmException e) { logger.debug(e.getMessage()); throw new RuntimeException(e); } catch (InvalidKeySpecException e) { logger.debug(e.getMessage()); throw new RuntimeException(e); } }