KeySpec keySpec = new PKCS8EncodedKeySpec( encodedKey ); try return KeyFactory.getInstance( "RSA" ).generatePrivate( keySpec ); return KeyFactory.getInstance( "DSA" ).generatePrivate( keySpec ); return KeyFactory.getInstance( "EC" ).generatePrivate( keySpec ); try ( DataInputStream in = new DataInputStream( new FileInputStream( privateKeyFile ) ) ) KeySpec keySpec = new PKCS8EncodedKeySpec( keyBytes ); return KeyFactory.getInstance( DEFAULT_ENCRYPTION ).generatePrivate( keySpec );
byte[] pubKeyBytes = new byte[pubKeyLength]; FileInputStream privIn = new FileInputStream(privateKey); FileInputStream pubIn = new FileInputStream(publicKey); privIn.read(privKeyBytes); pubIn.read(pubKeyBytes); pubIn.close(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes); crypto.keyPair = new KeyPair(keyFactory.generatePublic(publicKeySpec), keyFactory.generatePrivate(privateKeySpec)); crypto.base64 = base64;
/** * 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)); } }
protected static RSAPrivateKey generatePvtKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory factory = KeyFactory.getInstance("RSA"); return (RSAPrivateKey)factory.generatePrivate(spec); }
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));
public static PublicKey getPublicKeyByPublicKeyFile(String publicKeyFile) { if (publicKeyFile == null || publicKeyFile.length() == 0) { return ConfigTools.getPublicKey(null); } FileInputStream in = null; try { in = new FileInputStream(publicKeyFile); ByteArrayOutputStream out = new ByteArrayOutputStream(); int len = 0; byte[] b = new byte[512 / 8]; while ((len = in.read(b)) != -1) { out.write(b, 0, len); } byte[] publicKeyBytes = out.toByteArray(); X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes); KeyFactory factory = KeyFactory.getInstance("RSA", "SunRsaSign"); return factory.generatePublic(spec); } catch (Exception e) { throw new IllegalArgumentException("Failed to get public key", e); } finally { JdbcUtils.close(in); } }
public PrivateKey obtain_private_key(File private_key_file){ FileInputStream inpriv = new FileInputStream(private_key_file); byte[] bufferPriv = new byte[inpriv.available()]; inpriv.read(bufferPriv); inpriv.close(); KeyFactory constructor_claves = KeyFactory.getInstance("RSA"); KeySpec clave_raw = new PKCS8EncodedKeySpec(bufferPriv); return constructor_claves.generatePrivate(clave_raw); }
public static String decrypt(PublicKey publicKey, String cipherText) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); try { cipher.init(Cipher.DECRYPT_MODE, publicKey); } catch (InvalidKeyException e) { // 因为 IBM JDK 不支持私钥加密, 公钥解密, 所以要反转公私钥 // 也就是说对于解密, 可以通过公钥的参数伪造一个私钥对象欺骗 IBM JDK RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent()); Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec); cipher = Cipher.getInstance("RSA"); //It is a stateful object. so we need to get new one. cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey); } if (cipherText == null || cipherText.length() == 0) { return cipherText; } byte[] cipherBytes = Base64.base64ToByteArray(cipherText); byte[] plainBytes = cipher.doFinal(cipherBytes); return new String(plainBytes); }
/** * 使用模和指数生成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; } }
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());
byte[] dataByte = data.getBytes("UTf-8"); byte[] keyBytes = base64.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(fillMode); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = dataByte.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); cache = cipher.doFinal(dataByte, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(dataByte, offSet, inputLen - offSet);
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; }
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 ); }
PrivateKey signingKey = keyFactory.generatePrivate(signingRSAKey); RSAPublicKeySpec pub = keyFactory.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); RSAPrivateKeySpec priv = keyFactory.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class); 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);
/** * Encrypts data such that it can only be decrypted by the paired private certificate, which is held by the certificate owner. * <br><br> * Note that only a limited amount of data can be encrypted in this fashion - for large exchanges this should be used * to establish shared symmetric key which can then be used for the main exchange. * * @param data * @return The encrypted data */ public byte[] encrypt(byte[] data) { RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent); try { KeyFactory keyFactory = KeyFactory.getInstance(IdentityConstants.CERTIFICATE_ALGORITHM); PublicKey key = keyFactory.generatePublic(keySpec); Cipher cipher = Cipher.getInstance(IdentityConstants.CERTIFICATE_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(data); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new RuntimeException("Insufficient support for '" + IdentityConstants.CERTIFICATE_ALGORITHM + "', required for identity management", e); } catch (InvalidKeySpecException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) { throw new RuntimeException("Unexpected error during encryption", e); } }
@Override void computeK(byte[] f) throws GeneralSecurityException { final KeyFactory keyFactory = SecurityUtils.getKeyFactory("DH"); final PublicKey yourPubKey = keyFactory.generatePublic(new DHPublicKeySpec(new BigInteger(f), p, g)); agreement.doPhase(yourPubKey, true); setK(new BigInteger(1, agreement.generateSecret())); }
/** Creates a DSA private key. */ public static PrivateKey newDSAPrivateKey(String x, String p, String q, String g) throws GeneralSecurityException { return SecurityUtils.getKeyFactory("DSA").generatePrivate(new DSAPrivateKeySpec(new BigInteger(x, 16), new BigInteger(p, 16), new BigInteger(q, 16), new BigInteger(g, 16)) ); }
public KeyPair getKeyPair(String alias, char[] password) { try { synchronized (lock) { if (store == null) { synchronized (lock) { store = KeyStore.getInstance("jks"); store.load(resource.getInputStream(), this.password); } } } RSAPrivateCrtKey key = (RSAPrivateCrtKey) store.getKey(alias, password); RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec); return new KeyPair(publicKey, key); } catch (Exception e) { throw new IllegalStateException("Cannot load keys from store: " + resource, e); } }
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear); KeyFactory fact = KeyFactory.getInstance("DSA"); PrivateKey priv = fact.generatePrivate(keySpec); Arrays.fill(clear, (byte) 0); return priv; X509EncodedKeySpec spec = new X509EncodedKeySpec(data); KeyFactory fact = KeyFactory.getInstance("DSA"); return fact.generatePublic(spec); KeyFactory fact = KeyFactory.getInstance("DSA"); PKCS8EncodedKeySpec spec = fact.getKeySpec(priv, PKCS8EncodedKeySpec.class); byte[] packed = spec.getEncoded(); String key64 = base64Encode(packed); KeyFactory fact = KeyFactory.getInstance("DSA"); X509EncodedKeySpec spec = fact.getKeySpec(publ, X509EncodedKeySpec.class); return base64Encode(spec.getEncoded()); KeyPair pair = gen.generateKeyPair(); String pubKey = savePublicKey(pair.getPublic()); PublicKey pubSaved = loadPublicKey(pubKey); System.out.println(pair.getPublic()+"\n"+pubSaved);
/** 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))); }