private static byte[] encodePublicKey(PublicKey publicKey) throws InvalidKeyException { byte[] encodedPublicKey = null; if ("X.509".equals(publicKey.getFormat())) { encodedPublicKey = publicKey.getEncoded(); } if (encodedPublicKey == null) { try { encodedPublicKey = KeyFactory.getInstance(publicKey.getAlgorithm()) .getKeySpec(publicKey, X509EncodedKeySpec.class) .getEncoded(); } catch (NoSuchAlgorithmException e) { throw new InvalidKeyException( "Failed to obtain X.509 encoded form of public key " + publicKey + " of class " + publicKey.getClass().getName(), e); } catch (InvalidKeySpecException e) { throw new InvalidKeyException( "Failed to obtain X.509 encoded form of public key " + publicKey + " of class " + publicKey.getClass().getName(), e); } } if ((encodedPublicKey == null) || (encodedPublicKey.length == 0)) { throw new InvalidKeyException( "Failed to obtain X.509 encoded form of public key " + publicKey + " of class " + publicKey.getClass().getName()); } return encodedPublicKey; }
/** * Generates a self-signed certificate. These are used to identify servers. * * @return A matched pair of public and private certificates. */ public CertificatePair generateSelfSigned() { keyPairGenerator.initialize(KEY_SIZE); KeyPair kp = keyPairGenerator.genKeyPair(); try { RSAPublicKeySpec pub = keyFactory.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); RSAPrivateKeySpec priv = keyFactory.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class); String uuid = UUID.randomUUID().toString(); signer.initSign(kp.getPrivate(), new SecureRandom()); signer.update(uuid.getBytes(Charsets.UTF_8)); signer.update(pub.getModulus().toByteArray()); signer.update(pub.getPublicExponent().toByteArray()); byte[] rawSig = signer.sign(); BigInteger signature = new BigInteger(rawSig); PublicIdentityCertificate publicCert = new PublicIdentityCertificate(uuid, pub.getModulus(), pub.getPublicExponent(), signature); PrivateIdentityCertificate privateCert = new PrivateIdentityCertificate(priv.getModulus(), priv.getPrivateExponent()); return new CertificatePair(publicCert, privateCert); } catch (InvalidKeySpecException | SignatureException | InvalidKeyException e) { throw new RuntimeException("Unexpected exception generating certificate", e); } }
PKCS8EncodedKeySpec spec = fact.getKeySpec(priv, PKCS8EncodedKeySpec.class); byte[] packed = spec.getEncoded(); X509EncodedKeySpec spec = fact.getKeySpec(publ, X509EncodedKeySpec.class); return base64Encode(spec.getEncoded());
PrivateKey signingKey = keyFactory.generatePrivate(signingRSAKey); RSAPublicKeySpec pub = keyFactory.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); RSAPrivateKeySpec priv = keyFactory.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);
/** * Generate PEM content containing a {@link PublicKey}. * * @param target the target byte string builder (must not be {@code null}) * @param publicKey the {@link PublicKey} (must not be {@code null}) */ public static void generatePemPublicKey(ByteStringBuilder target, PublicKey publicKey) { Assert.checkNotNullParam("target", target); Assert.checkNotNullParam("publicKey", publicKey); try { KeyFactory instance = KeyFactory.getInstance(publicKey.getAlgorithm()); X509EncodedKeySpec keySpec = instance.getKeySpec(publicKey, X509EncodedKeySpec.class); generatePemContent(target, PUBLIC_KEY_FORMAT, ByteIterator.ofBytes(keySpec.getEncoded())); } catch (Exception e) { throw log.publicKeyParseError(e); } }
final PublicKey publicKey = credential.castAndApply(PublicKeyCredential.class, PublicKeyCredential::getPublicKey); final KeyFactory keyFactory = KeyFactory.getInstance(publicKey.getAlgorithm()); final X509EncodedKeySpec keySpec = keyFactory.getKeySpec(keyFactory.translateKey(publicKey), X509EncodedKeySpec.class); final byte[] encoded = keySpec.getEncoded(); entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(encoded, DATA_OID)); final X509EncodedKeySpec publicSpec = keyFactory.getKeySpec(keyFactory.translateKey(publicKey), X509EncodedKeySpec.class); final PKCS8EncodedKeySpec privateSpec = keyFactory.getKeySpec(keyFactory.translateKey(privateKey), PKCS8EncodedKeySpec.class); final DEREncoder encoder = new DEREncoder(); encoder.startSequence();
final KeyFactory keyFactory = KeyFactory.getInstance(publicKeyAlgorithm); final Key translatedKey = keyFactory.translateKey(publicKey); keySpec = keyFactory.getKeySpec(translatedKey, X509EncodedKeySpec.class); } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException e) { throw log.invalidKeyForCert(publicKeyAlgorithm, e);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); KeyPair kp = kpg.genKeyPair(); KeyFactory fact = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); saveToFile(PUBLIC_KEY_FILE, pub.getModulus(), pub.getPublicExponent()); RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class); saveToFile(PRIVATE_KEY_FILE, priv.getModulus(), priv.getPrivateExponent());
// key pair is in 'kp' KeyFactory kf = KeyFactory.getInstance("RSA"); RSAPrivateCrtKeySpec ks = kf.getKeySpec( kp.getPrivate(), RSAPrivateCrtKeySpec.class); System.out.println("<RSAKeyValue>"); System.out.println(" <Modulus>" + ks.getModulus() + "</Modulus>"); System.out.println(" <Exponent>" + ks.getPublicExponent() + "</Exponent>"); System.out.println(" <P>" + ks.getPrimeP() + "</P>"); System.out.println(" <Q>" + ks.getPrimeQ() + "</Q>"); System.out.println(" <DP>" + ks.getPrimeExponentP() + "</DP>"); System.out.println(" <DQ>" + ks.getPrimeExponentQ() + "</DQ>"); System.out.println(" <InverseQ>" + ks.getCrtCoefficient() + "</InverseQ>"); System.out.println(" <D>" + ks.getPrivateExponent() + "</D>"); System.out.println("</RSAKeyValue>");
/** * Returns base64 encoded PublicKey * @param key PublicKey * @return public key encoded string */ public static String encodePublicKey(PublicKey key) { try { KeyFactory keyFactory = CertUtils.getKeyFactory(); if (keyFactory == null) return null; X509EncodedKeySpec spec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class); return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()), Charset.forName("UTF-8")); } catch (InvalidKeySpecException e) { s_logger.error("Unable to get KeyFactory:" + e.getMessage()); } return null; }
/** * Returns base64 encoded PrivateKey * @param key PrivateKey * @return privatekey encoded string */ public static String encodePrivateKey(PrivateKey key) { try { KeyFactory keyFactory = CertUtils.getKeyFactory(); if (keyFactory == null) return null; PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class); return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()), Charset.forName("UTF-8")); } catch (InvalidKeySpecException e) { s_logger.error("Unable to get KeyFactory:" + e.getMessage()); } return null; }
public static ECPrivateKey ecPrivateKeyFromPrivateKey(PrivateKey key) { ECPrivateKey k; try { KeyFactory f = KeyFactory.getInstance("EC"); ECPrivateKeySpec s = f.getKeySpec(key, ECPrivateKeySpec.class); k = (ECPrivateKey) f.generatePrivate(s); } catch (NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException | ClassCastException ex) { LOGGER.warn("Could not convert key to EC private key!"); LOGGER.debug(ex); return null; } return k; }
public static RSAPrivateKey rsaPrivateKeyFromPrivateKey(PrivateKey key) { RSAPrivateKey k; try { KeyFactory f = KeyFactory.getInstance("RSA"); RSAPrivateKeySpec s = f.getKeySpec(key, RSAPrivateKeySpec.class); k = (RSAPrivateKey) f.generatePrivate(s); } catch (NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException | ClassCastException ex) { LOGGER.warn("Could not convert key to EC private key!"); LOGGER.debug(ex); return null; } return k; }
private boolean isInSecureHardware() { try { KeyFactory factory = KeyFactory.getInstance(privateKey.getAlgorithm(), keystoreName); KeyInfo keyInfo = factory.getKeySpec(privateKey, KeyInfo.class); return keyInfo.isInsideSecureHardware(); } catch (GeneralSecurityException e) { Log.w(TAG, "Could not determine if private key is in secure hardware or not"); } return false; }
// receiving public key from where you store it Key publicKey = YourCarrierClass.getYourVariablePublic(); KeyFactory fact; // initializing public key variable RSAPublicKeySpec pub = new RSAPublicKeySpec(BigInteger.ZERO, BigInteger.ZERO); try { fact = KeyFactory.getInstance("RSA"); pub = fact.getKeySpec(publicKey, RSAPublicKeySpec.class); } catch(NoSuchAlgorithmException e1) { } catch(InvalidKeySpecException e) { } // now you should pass Modulus string onto your html(jsp) in such way String htmlUsedModulus = pub.getModulus().toString(16); // send somehow this String to page, so javascript can use it
RSAPrivateKeySpec getPrivateKeySpec() { try { return getKeyFactory().getKeySpec(getPrivateKey(), RSAPrivateKeySpec.class); } catch (InvalidKeySpecException ex) { throw new Error(ex); } }
KeyFactory fact = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class); saveToFile("public.key", pub.getModulus(), pub.getPublicExponent()); saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());
public static String publicKey2String(Key key) throws NoSuchAlgorithmException, InvalidKeySpecException{ sun.misc.BASE64Encoder base64encoder = new sun.misc.BASE64Encoder(); KeyFactory keyFactory= KeyFactory.getInstance("RSA"); X509EncodedKeySpec x509EncodedKeySpec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class); byte[] buffer1 = x509EncodedKeySpec.getEncoded(); return base64encoder.encode(buffer1); }
public RSAPublicKeySpec getPublicKey() throws GeneralSecurityException { KeyFactory fact = asymmetricCipher.getKeyFactory(); ClearText key = getKey(ASYMMETRIC_KEY_ALIAS, null); if (key == null) return null; return fact.getKeySpec(key.asKeyPair().getPublic(), RSAPublicKeySpec.class); }
public static String privateKey2String(Key key) throws NoSuchAlgorithmException, InvalidKeySpecException{ sun.misc.BASE64Encoder base64encoder = new sun.misc.BASE64Encoder(); KeyFactory keyFactory= KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec pKCS8EncodedKeySpec = keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class); byte[] buffer1 = pKCS8EncodedKeySpec.getEncoded(); return base64encoder.encode(buffer1); }