private static byte[] encodePublicKey(PublicKey publicKey) throws InvalidKeyException, NoSuchAlgorithmException { 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 (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; }
/** * Saves a key pair. * * @param keyPair the key pair to save * @throws IOException if the files cannot be written * @since 1.0.0 */ public void save(KeyPair keyPair) throws IOException { LOGGER.info("Saving key pair"); final PrivateKey privateKey = keyPair.getPrivate(); final PublicKey publicKey = keyPair.getPublic(); // Store Public Key final File publicKeyFile = getKeyPath(publicKey); publicKeyFile.getParentFile().mkdirs(); // make directories if they do not exist final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); try (FileOutputStream fos = new FileOutputStream(publicKeyFile)) { fos.write(x509EncodedKeySpec.getEncoded()); } // Store Private Key. final File privateKeyFile = getKeyPath(privateKey); privateKeyFile.getParentFile().mkdirs(); // make directories if they do not exist final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); try (FileOutputStream fos = new FileOutputStream(privateKeyFile)) { fos.write(pkcs8EncodedKeySpec.getEncoded()); } }
/** * RSA验签名检查 * @param content 待签名数据 * @param sign 签名值 * @param ali_public_key 支付宝公钥 * @param input_charset 编码格式 * @return 布尔值 */ public static boolean verify(String content, String sign, String ali_public_key, String input_charset) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] encodedKey = Base64.decode(ali_public_key); PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); java.security.Signature signature = java.security.Signature .getInstance(SIGN_ALGORITHMS); signature.initVerify(pubKey); signature.update( content.getBytes(input_charset) ); boolean bverify = signature.verify( Base64.decode(sign) ); return bverify; } catch (Exception e) { e.printStackTrace(); } return false; }
/** * 校验数字签名 * * @param data 加密数据 * @param publicKey 公钥 * @param sign 数字签名 * @return * @throws Exception */ public static boolean verify(byte[] data, String publicKey, String sign) throws Exception { //解密公钥 byte[] keyBytes = Base64.decode(publicKey.getBytes(), Base64.DEFAULT); //构造X509EncodedKeySpec对象 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); //指定加密算法 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //取公钥匙对象 PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(publicKey2); signature.update(data); //验证签名是否正常 return signature.verify(Base64.decode(sign, Base64.DEFAULT)); }
/** * 用公钥加密 * * @param data * @param key * @return * @throws Exception */ public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception { byte[] keyBytes = BASE64.decode(key); // 对公钥解密 // 取得公钥 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType()); Key publicKey = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); }
@Override public void onEnable() { instance = this; try { mojangPublicKey = KeyFactory.getInstance("EC").generatePublic( new X509EncodedKeySpec(Base64 .getDecoder() .decode("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V") ) ); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { e.printStackTrace(); } networkManager = new NetworkManager(); }
public static PublicKey getPublicKey(String publicKeyText) { if (publicKeyText == null || publicKeyText.length() == 0) { publicKeyText = DecryptUtil.DEFAULT_PUBLIC_KEY_STRING; } try { byte[] publicKeyBytes = Base64.base64ToByteArray(publicKeyText); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec( publicKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(x509KeySpec); } catch (Exception e) { throw new IllegalArgumentException("Failed to get public key", e); } }
/** * 校验 * * @param data 待校验数据 * @param publicKey 公钥 * @param sign 数字签名 * @return boolean 校验成功返回true 失败返回false * @throws Exception */ public static boolean verify(byte[] data, byte[] publicKey, byte[] sign) throws Exception { // 转换公钥材料 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); // 实例化密钥工厂 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); // 生成公钥 PublicKey pubKey = keyFactory.generatePublic(keySpec); // 实例化Signature Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); // 初始化Signature signature.initVerify(pubKey); // 更新 signature.update(data); // 验证 return signature.verify(sign); }
/** * 校验 * * @param data * 待校验数据 * @param publicKey * 公钥 * @param sign * 数字签名 * @return boolean 校验成功返回true 失败返回false * @throws Exception */ public static boolean verify(byte[] data, byte[] publicKey, byte[] sign) throws Exception { // 转换公钥材料 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); // 实例化密钥工厂 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); // 生成公钥 PublicKey pubKey = keyFactory.generatePublic(keySpec); // 实例化Signature Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); // 初始化Signature signature.initVerify(pubKey); // 更新 signature.update(data); // 验证 return signature.verify(sign); }
protected PublicKey engineGeneratePublic( KeySpec keySpec) throws InvalidKeySpecException { if (keySpec instanceof X509EncodedKeySpec) { try { return generatePublic(SubjectPublicKeyInfo.getInstance(((X509EncodedKeySpec)keySpec).getEncoded())); } catch (Exception e) { throw new InvalidKeySpecException("encoded key spec not recognised"); } } else { throw new InvalidKeySpecException("key spec not recognised"); } }
public KeyPair getKeyPair(PEMKeyPair keyPair) throws PEMException { try { String algorithm = keyPair.getPrivateKeyInfo().getPrivateKeyAlgorithm().getAlgorithm().getId(); if (X9ObjectIdentifiers.id_ecPublicKey.getId().equals(algorithm)) { algorithm = "ECDSA"; } KeyFactory keyFactory = helper.createKeyFactory(algorithm); return new KeyPair(keyFactory.generatePublic(new X509EncodedKeySpec(keyPair.getPublicKeyInfo().getEncoded())), keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyPair.getPrivateKeyInfo().getEncoded()))); } catch (Exception e) { throw new PEMException("unable to convert key pair: " + e.getMessage(), e); } }
/** * 用公钥解密 * * @param data * @param key * @return * @throws Exception */ public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception { byte[] keyBytes = BASE64.decode(key); // 对密钥解密 // 取得公钥 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType()); Key publicKey = keyFactory.generatePublic(x509KeySpec); // 对数据解密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicKey); return cipher.doFinal(data); }
/** * Convert encoded private and public keys (bytes) to Private / PublicKey * interfaces and generate a KeyPair from them in order to construct a * Wallet object in the signIn method<br> * <b>Two different encoding</b> * * @param publicKeyBytes the public key with encoding X509 * @param privateKeyBytes the private key with encoding PKCS8 * @return the key pair */ public static KeyPair createKeyPairFromEncodedKeys(byte[] publicKeyBytes, byte[] privateKeyBytes) { // Generate specs final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); try { // Create PublicKey and PrivateKey interfaces using the factory final PrivateKey privateKey = dsaKeyFactory.generatePrivate(privateKeySpec); final PublicKey publicKey = dsaKeyFactory.generatePublic(publicKeySpec); return new KeyPair(publicKey, privateKey); } catch (InvalidKeySpecException ex) { logAndAbort("Unable to create key pair. Abort!", ex); } return null; }
private PublicKey getDERPublicKeyFromPEM(String key) throws Exception { try { // strip of header, footer, newlines, whitespaces String publicKeyPEM = key .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", "") .replaceAll("\\s", ""); // decode to get the binary DER representation byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER)); return publicKey; } catch (Exception e) { throw new InvalidConfig("Invalid JWE public key"); } }
@Override protected GMSEncrypt clone() throws CloneNotSupportedException { try { GMSEncrypt gmsEncrypt = new GMSEncrypt(); gmsEncrypt.localMember = this.localMember; gmsEncrypt.dhSKAlgo = this.dhSKAlgo; gmsEncrypt.services = this.services; X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(this.dhPublicKey.getEncoded()); KeyFactory keyFact = KeyFactory.getInstance("DH"); gmsEncrypt.dhPublicKey = keyFact.generatePublic(x509KeySpec); final String format = this.dhPrivateKey.getFormat(); System.out.println("private key format " + format); System.out.println("public ksy format " + this.dhPublicKey.getFormat()); PKCS8EncodedKeySpec x509KeySpecPKey = new PKCS8EncodedKeySpec(this.dhPrivateKey.getEncoded()); keyFact = KeyFactory.getInstance("DH"); // PublicKey pubKey = keyFact.generatePublic(x509KeySpec); gmsEncrypt.dhPrivateKey = keyFact.generatePrivate(x509KeySpecPKey); return gmsEncrypt; } catch (Exception e) { throw new RuntimeException("Unable to clone", e); } }
/** * Creates a RSA Public Key from a PEM String * * @param pemPublicKey public key in PEM format * @return a RSA public key */ public static PublicKey parseRSAPublicKey(final String pemPublicKey) throws GeneralSecurityException { try { String publicKeyString = pemPublicKey .replace(PEM_PUBLIC_START, "") .replace(PEM_PUBLIC_END, "") .replaceAll("\\s", ""); byte[] keyBytes = Base64.decode(publicKeyString.getBytes("UTF-8")); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(spec); } catch (InvalidKeySpecException | NoSuchAlgorithmException | UnsupportedEncodingException e) { throw new GeneralSecurityException(e); } }
public static RSAPublicKey decodeRSAPublicKey(String key, ExceptionInterceptor interceptor) throws SQLException { try { if (key == null) { throw new SQLException("key parameter is null"); } int offset = key.indexOf("\n") + 1; int len = key.indexOf("-----END PUBLIC KEY-----") - offset; // TODO: use standard decoders with Java 6+ byte[] certificateData = Base64Decoder.decode(key.getBytes(), offset, len); X509EncodedKeySpec spec = new X509EncodedKeySpec(certificateData); KeyFactory kf = KeyFactory.getInstance("RSA"); return (RSAPublicKey) kf.generatePublic(spec); } catch (Exception ex) { throw SQLError.createSQLException("Unable to decode public key", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, ex, interceptor); } }
/** * Generates a public key object from the provided key specification * (key material). * * @param keySpec the specification (key material) of the public key * * @return the public key * * @exception InvalidKeySpecException if the given key specification * is inappropriate for this key factory to produce a public key. */ protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecException { try { if (keySpec instanceof DHPublicKeySpec) { DHPublicKeySpec dhPubKeySpec = (DHPublicKeySpec)keySpec; return new DHPublicKey(dhPubKeySpec.getY(), dhPubKeySpec.getP(), dhPubKeySpec.getG()); } else if (keySpec instanceof X509EncodedKeySpec) { return new DHPublicKey (((X509EncodedKeySpec)keySpec).getEncoded()); } else { throw new InvalidKeySpecException ("Inappropriate key specification"); } } catch (InvalidKeyException e) { throw new InvalidKeySpecException ("Inappropriate key specification", e); } }
public static boolean doCheck(String content, String sign, String publicKey) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] encodedKey = Base64.decode(publicKey); PublicKey pubKey = keyFactory .generatePublic(new X509EncodedKeySpec(encodedKey)); java.security.Signature signature = java.security.Signature .getInstance(SIGN_ALGORITHMS); signature.initVerify(pubKey); signature.update(content.getBytes()); boolean bverify = signature.verify(Base64.decode(sign)); return bverify; } catch (Exception e) { e.printStackTrace(); } return false; }
/** * Load a raw base64 encoded key. * @param key The base64 encoded key. * @return Public key */ public static PublicKey loadPublicKey(String key) { KeyFactory kf = getKeyFactory(); if(kf == null) { return null; } byte[] rawKey = Base64.decode(key, Base64.DEFAULT); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(rawKey); try { return kf.generatePublic(pubKeySpec); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; }
public boolean verify() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidKeyException, SignatureException { final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey); final KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN"); final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); final byte[] sigToVerify = sign; final Signature sig = Signature.getInstance("SHA1withDSA", "SUN"); sig.initVerify(pubKey); sig.update(data, 0, data.length); final boolean verifies = sig.verify(sigToVerify); return verifies; }
/** * Create a new PublicKey from encoded X.509 data */ public static PublicKey decodePublicKey(byte[] encodedKey) { try { EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey); KeyFactory keyfactory = KeyFactory.getInstance("RSA"); return keyfactory.generatePublic(encodedkeyspec); } catch (NoSuchAlgorithmException var3) { ; } catch (InvalidKeySpecException var4) { ; } LOGGER.error("Public key reconstitute failed!"); return null; }
private static PublicKey generatePublicKeyFromString(String key, String algorithm) { PublicKey publicKey = null; if(key.length()>1){ key = key.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "") .replaceAll("\\s+", "").replaceAll("\\r+", "").replaceAll("\\n+", ""); byte[] keyByteArray = java.util.Base64.getDecoder().decode(key); try { KeyFactory kf = KeyFactory.getInstance(algorithm); EncodedKeySpec keySpec = new X509EncodedKeySpec(keyByteArray); publicKey = kf.generatePublic(keySpec); } catch (Exception e) { ConsoleOut.output(e.getMessage()); } } return publicKey; }
private static String getPEMPublicKeyFromDER(PublicKey publicKey) { String begin = "-----BEGIN PUBLIC KEY-----"; String end = "-----END PUBLIC KEY-----"; X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); String key = Base64.getEncoder().encodeToString(x509EncodedKeySpec.getEncoded()); return begin + "\n" + key + "\n" + end; }
/** * 加密<br> * 用公钥加密 * * @param data 明文 * @param key 公钥 * @return 密文 * @throws Exception 加密异常 */ public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception { // 对公钥解密 byte[] keyBytes = decryptBASE64(key); // 取得公钥 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicKey = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); }
public SymmetricKeyGenerator(DHPublicKey pubKey, DHPrivateKey priKey) throws Exception { byte[] publicKey = pubKey.getEncoded(); byte[] privateKey = priKey.getEncoded(); java.security.KeyFactory keyFactory = KeyFactory.getInstance("DH"); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey); PublicKey pubKey1 = keyFactory.generatePublic(x509KeySpec); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey); PrivateKey priKey1 = keyFactory.generatePrivate(pkcs8KeySpec); KeyAgreement keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm()); keyAgree.init(priKey1); keyAgree.doPhase(pubKey1, true); secretKey = keyAgree.generateSecret(KEY_ALGORITHM); }
private static PublicKey getPublicKey() throws IOException, GeneralSecurityException { InputStream inputStr = PasswdEncryption.class.getResourceAsStream("pubKey"); // NOI18N byte[] encodedKey = new byte[inputStr.available()]; try { inputStr.read(encodedKey); } finally { inputStr.close(); } X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey); KeyFactory kf = KeyFactory.getInstance("RSA"); // NOI18N PublicKey publicKey = kf.generatePublic(publicKeySpec); return publicKey; }
@Override protected final PublicKey createInstance() throws Exception { logger.debug("Creating public key instance from [{}] using [{}]", this.resource.getFilename(), this.algorithm); try (InputStream pubKey = this.resource.getInputStream()) { final byte[] bytes = new byte[pubKey.available()]; pubKey.read(bytes); final X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(bytes); final KeyFactory factory = KeyFactory.getInstance(this.algorithm); return factory.generatePublic(pubSpec); } }
@Override protected final PublicKey createInstance() throws Exception { logger.debug("Creating public key instance from [{}] using [{}]", this.resource.getFilename(), this.algorithm); try (final InputStream pubKey = this.resource.getInputStream()) { final byte[] bytes = new byte[pubKey.available()]; pubKey.read(bytes); final X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(bytes); final KeyFactory factory = KeyFactory.getInstance(this.algorithm); return factory.generatePublic(pubSpec); } }
public static boolean verify(String messageText, String signature, String publicKey) throws Exception { byte[] publicKeyByteArr = Base64.decode(publicKey); PublicKey key = KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(publicKeyByteArr)); Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(key); sig.update(messageText.getBytes()); return sig.verify(Base64.decode(signature)); }