/** * Gets the public part of the RSA key that represents the server identity. */ public PublicKey getIdentity() throws GeneralSecurityException { if (identity==null) return null; byte[] image = Base64.decodeBase64(identity); return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(image)); } }
/** * Try to generate a PublicKey for a given {@code keySpec} and * {@code algorithm} identifier. If there a problem generating the key like * a missing {@code KeyFactory} or invalid {@code KeySpec}, it will return * {@code null}. */ private static PublicKey generateKeyForAlgorithm(KeySpec keySpec, String algorithm) { try { return KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (InvalidKeySpecException ignored) { } catch (NoSuchAlgorithmException ignored) { } return null; }
byte[] privateKeyBytes; byte[] publicKeyBytes; KeyFactory kf = KeyFactory.getInstance("RSA"); // or "EC" or whatever PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
BigInteger modulus = new BigInteger("F56D...", 16); BigInteger pubExp = new BigInteger("010001", 16); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, pubExp); RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec); Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] cipherData = cipher.doFinal(text.getBytes());
public static KeyPair loadKey(String pemString, String passwd) throws IOException, GeneralSecurityException { Object key = PEMDecoder.decode(pemString.toCharArray(), passwd); if (key instanceof com.trilead.ssh2.signature.RSAPrivateKey) { com.trilead.ssh2.signature.RSAPrivateKey x = (com.trilead.ssh2.signature.RSAPrivateKey)key; return x.toJCEKeyPair(); } if (key instanceof com.trilead.ssh2.signature.DSAPrivateKey) { com.trilead.ssh2.signature.DSAPrivateKey x = (com.trilead.ssh2.signature.DSAPrivateKey)key; KeyFactory kf = KeyFactory.getInstance("DSA"); return new KeyPair( kf.generatePublic(new DSAPublicKeySpec(x.getY(), x.getP(), x.getQ(), x.getG())), kf.generatePrivate(new DSAPrivateKeySpec(x.getX(), x.getP(), x.getQ(), x.getG()))); } throw new UnsupportedOperationException("Unrecognizable key format: " + key); }
@Test public void testSignAndVerify() throws Exception { BigInteger x = new BigInteger(new byte[] { 58, 19, -71, -30, 89, -111, 75, 98, 110, 38, -56, -23, 68, 74, -40, 17, -30, 37, 50, 35 }); BigInteger y = new BigInteger(new byte[] { 32, -91, -39, 54, 19, 14, 26, 113, -109, -92, -45, 83, -86, 23, -103, 108, 102, 86, 110, 78, -45, -41, -37, 38, -94, -92, -124, -36, -93, 92, 127, 113, 97, -119, -10, -73, -41, -45, 98, -104, -54, -9, -92, 66, 15, 31, 68, -32, 32, -121, -51, 68, 29, 100, 59, 60, 109, 111, -81, 80, 7, 127, 116, -107, 88, -114, -114, -69, 41, -15, 59, 81, 70, 9, -113, 36, 119, 28, 16, -127, -65, 32, -19, 109, -27, 24, -48, -80, 84, 47, 119, 25, 57, -118, -66, -22, -105, -11, 112, 16, -91, -127, 62, 23, 89, -17, -43, -105, -4, -43, 60, 42, -81, -95, -27, -8, 98, -37, 120, 80, -76, 93, -24, -104, -117, 38, -56, -68 }); BigInteger p = new BigInteger(new byte[] { 0, -3, 127, 83, -127, 29, 117, 18, 41, 82, -33, 74, -100, 46, -20, -28, -25, -10, 17, -73, 82, 60, -17, 68, 0, -61, 30, 63, -128, -74, 81, 38, 105, 69, 93, 64, 34, 81, -5, 89, 61, -115, 88, -6, -65, -59, -11, -70, 48, -10, -53, -101, 85, 108, -41, -127, 59, -128, 29, 52, 111, -14, 102, 96, -73, 107, -103, 80, -91, -92, -97, -97, -24, 4, 123, 16, 34, -62, 79, -69, -87, -41, -2, -73, -58, 27, -8, 59, 87, -25, -58, -88, -90, 21, 15, 4, -5, -125, -10, -45, -59, 30, -61, 2, 53, 84, 19, 90, 22, -111, 50, -10, 117, -13, -82, 43, 97, -41, 42, -17, -14, 34, 3, 25, -99, -47, 72, 1, -57 }); BigInteger q = new BigInteger(new byte[] { 0, -105, 96, 80, -113, 21, 35, 11, -52, -78, -110, -71, -126, -94, -21, -124, 11, -16, 88, 28, -11 }); BigInteger g = new BigInteger(new byte[] { 0, -9, -31, -96, -123, -42, -101, 61, -34, -53, -68, -85, 92, 54, -72, 87, -71, 121, -108, -81, -69, -6, 58, -22, -126, -7, 87, 76, 11, 61, 7, -126, 103, 81, 89, 87, -114, -70, -44, 89, 79, -26, 113, 7, 16, -127, -128, -76, 73, 22, 113, 35, -24, 76, 40, 22, 19, -73, -49, 9, 50, -116, -56, -90, -31, 60, 22, 122, -117, 84, 124, -115, 40, -32, -93, -82, 30, 43, -77, -90, 117, -111, 110, -93, 127, 11, -6, 33, 53, 98, -15, -5, 98, 122, 1, 36, 59, -52, -92, -15, -66, -88, 81, -112, -119, -88, -125, -33, -31, 90, -27, -97, 6, -110, -117, 102, 94, -128, 123, 85, 37, 100, 1, 76, 59, -2, -49, 73, 42 }); byte[] data = "The Magic Words are Squeamish Ossifrage".getBytes(IOUtils.UTF8); // A previously signed and verified signature using the data and DSA key parameters above. byte[] dataSig = new byte[] { 0, 0, 0, 7, 115, 115, 104, 45, 100, 115, 115, 0, 0, 0, 40, 40, -71, 33, 105, -89, -107, 8, 26, -13, -90, 73, -103, 105, 112, 7, -59, -66, 46, 85, -27, 20, 82, 22, -113, -75, -86, -121, -42, -73, 78, 66, 93, -34, 39, -50, -93, 27, -5, 37, -92 }; SignatureDSA signatureForSigning = new SignatureDSA(); signatureForSigning.initSign(keyFactory.generatePrivate(new DSAPrivateKeySpec(x, p, q, g))); signatureForSigning.update(data); byte[] sigBlob = signatureForSigning.encode(signatureForSigning.sign()); byte[] sigFull = new Buffer.PlainBuffer().putString("ssh-dss").putBytes(sigBlob).getCompactData(); SignatureDSA signatureForVerifying = new SignatureDSA(); signatureForVerifying.initVerify(keyFactory.generatePublic(new DSAPublicKeySpec(y, p, q, g))); signatureForVerifying.update(data); Assert.assertTrue("Failed to verify signature: " + Arrays.toString(sigFull), signatureForVerifying.verify(sigFull)); signatureForVerifying.update(data); Assert.assertTrue("Failed to verify signature: " + Arrays.toString(dataSig), signatureForVerifying.verify(dataSig)); }
private static PublicKey toPublicKey(KeyFactory kf, BigInteger modulus, BigInteger publicExponent) { try { return kf.generatePublic(new RSAPublicKeySpec(modulus, publicExponent)); } catch (InvalidKeySpecException e) { throw new JwtException("Failed to generate RSA public key", e); } }
private RSAPublicKey key() throws InvalidKeySpecException { byte[] decoded = Base64.getDecoder().decode(VERIFY_KEY.getBytes()); EncodedKeySpec spec = new X509EncodedKeySpec(decoded); return (RSAPublicKey) kf.generatePublic(spec); }
public static String encrypt(byte[] keyBytes, String plainText) throws Exception { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory factory = KeyFactory.getInstance("RSA", "SunRsaSign"); PrivateKey privateKey = factory.generatePrivate(spec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); try { cipher.init(Cipher.ENCRYPT_MODE, privateKey); } catch (InvalidKeyException e) { //For IBM JDK, 原因请看解密方法中的说明 RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey; RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent()); Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec); cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, fakePublicKey); } byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8")); String encryptedString = Base64.byteArrayToBase64(encryptedBytes); return encryptedString; }
private RSAPublicKey getKey() { try { if (key == null) { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); key = (RSAPublicKey)keyFactory.generatePublic(new X509EncodedKeySpec(Util.fromHexString(keyImage))); } return key; } catch (GeneralSecurityException e) { throw new Error(e); // impossible } }
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent); KeyFactory factory = KeyFactory.getInstance("RSA"); PublicKey pub = factory.generatePublic(spec); Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(pub); verifier.update(url.getBytes("UTF-8")); // Or whatever interface specifies. boolean okay = verifier.verify(signature);
@BeforeClass public void setup() throws InvalidKeySpecException, NoSuchAlgorithmException, IOException { KeyFactory keyfactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyfactory.generatePrivate(Pems.privateKeySpec(Payloads.newStringPayload(PRIVATE_KEY))); PublicKey publicKey = keyfactory.generatePublic(Pems.publicKeySpec(Payloads.newStringPayload(PUBLIC_KEY))); keyPair = new KeyPair(publicKey, privateKey); openSshKey = SshKeys.encodeAsOpenSSH(RSAPublicKey.class.cast(publicKey)); }
/** * Verifies that we are talking to a peer that actually owns the private key corresponding to the public key we get. */ public PublicKey verifyIdentity(byte[] sharedSecret) throws IOException, GeneralSecurityException { try { String serverKeyAlgorithm = readUTF(); PublicKey spk = KeyFactory.getInstance(serverKeyAlgorithm).generatePublic(readKey()); // verify the identity of the server Signature sig = Signature.getInstance("SHA1with"+serverKeyAlgorithm); sig.initVerify(spk); sig.update(spk.getEncoded()); sig.update(sharedSecret); sig.verify((byte[]) readObject()); return spk; } catch (ClassNotFoundException e) { throw new Error(e); // impossible } }
@Override public PublicKey readPubKeyFromBuffer(Buffer<?> buf) throws GeneralSecurityException { final BigInteger e, n; try { e = buf.readMPInt(); n = buf.readMPInt(); } catch (Buffer.BufferException be) { throw new GeneralSecurityException(be); } final KeyFactory keyFactory = SecurityUtils.getKeyFactory("RSA"); return keyFactory.generatePublic(new RSAPublicKeySpec(n, e)); }
protected void handle(DhHeader hdr, Address sender) { try { PublicKey pub_key=dh_key_factory.generatePublic(new X509EncodedKeySpec(hdr.dh_key)); switch(hdr.type) { case SECRET_KEY_REQ: handleSecretKeyRequest(pub_key, sender); break; case SECRET_KEY_RSP: handleSecretKeyResponse(pub_key, hdr.encrypted_secret_key, hdr.secret_key_version, sender); break; default: log.warn("unknown header type %d", hdr.type); } } catch(Throwable t) { log.error(String.format("failed handling request %s", hdr), t); } }
public static Key decodeTransmittedKey( byte[] sessionKey, byte[] transmittedKey, boolean privateKey ) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { KeySpec keySpec = null; Key keyKey = null; if ( transmittedKey == null || sessionKey == null ) { return null; } if ( !privateKey ) { keySpec = new X509EncodedKeySpec( sessionKey ); keyKey = KeyFactory.getInstance( PUBLIC_KEY_ALGORITHM ).generatePublic( keySpec ); } else { keySpec = new PKCS8EncodedKeySpec( sessionKey ); keyKey = KeyFactory.getInstance( PUBLIC_KEY_ALGORITHM ).generatePrivate( keySpec ); } Cipher keyCipher = Cipher.getInstance( TRANSMISSION_CIPHER_PARAMS ); keyCipher.init( Cipher.UNWRAP_MODE, keyKey ); return keyCipher.unwrap( transmittedKey, SINGLE_KEY_ALGORITHM, Cipher.SECRET_KEY ); }
import java.io.*; import java.nio.*; import java.security.*; import java.security.spec.*; public class PublicKeyReader { public static PublicKey get(String filename) throws Exception { byte[] keyBytes = Files.readAllBytes(new File(filename).toPath()); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(spec); } }
/** * 使用模和指数生成RSA公钥 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA * /None/NoPadding】 * * @param modulus 模 * @param exponent 指数 * @return */ public static RSAPublicKey getPublicKey(String modulus, String exponent) { try { BigInteger b1 = new BigInteger(modulus); BigInteger b2 = new BigInteger(exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } catch (Exception e) { e.printStackTrace(); return null; } }
public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException { KeyPair keyPair; PublicKey otherHalf; if (side) { AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH"); paramGen.init(keySize); KeyPairGenerator dh = KeyPairGenerator.getInstance("DH"); dh.initialize(paramGen.generateParameters().getParameterSpec(DHParameterSpec.class)); keyPair = dh.generateKeyPair(); // send a half and get a half writeKey(keyPair.getPublic()); otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey()); } else { otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey()); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH"); keyPairGen.initialize(((DHPublicKey) otherHalf).getParams()); keyPair = keyPairGen.generateKeyPair(); // send a half and get a half writeKey(keyPair.getPublic()); } KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(keyPair.getPrivate()); ka.doPhase(otherHalf, true); return ka; }
/** Creates an RSA public key. */ public static PublicKey newRSAPublicKey(String modulus, String exponent) throws GeneralSecurityException { return SecurityUtils.getKeyFactory("RSA").generatePublic(new RSAPublicKeySpec(new BigInteger(modulus, 16), new BigInteger(exponent, 16))); }