Java 类java.security.spec.PKCS8EncodedKeySpec 实例源码

项目:Alpine    文件:KeyManager.java   
/**
 * 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());
    }
}
项目:java-learn    文件:DHUtil.java   
/**
 * 根据对方的公钥和自己的私钥生成本地密钥
 */
public static byte[] getSecretKey(byte[] publicKey, byte[] privateKey) throws Exception{
    //实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance("DH");
    //将公钥从字节数组转换为publicKey
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKey);
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
    //将私钥从字节数组转换为privateKey
    PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(privateKey);
    PrivateKey priKey = keyFactory.generatePrivate(priKeySpec);
    //准备根据以上公钥和私钥生成本地密钥SecretKey
    //先实例化KeyAgreement
    KeyAgreement keyAgreement = KeyAgreement.getInstance("DH");
    //用自己的私钥初始化keyAgreement
    keyAgreement.init(priKey);
    //结合对方的公钥进行运算
    keyAgreement.doPhase(pubKey, true);
    //开始生成本地密钥secretKey   密钥算法为对称密码算法
    SecretKey secretKey = keyAgreement.generateSecret("DES");  //DES、3DES、AES
    return secretKey.getEncoded();
}
项目:epay    文件:RSA.java   
/**
* RSA签名
* @param content 待签名数据
* @param privateKey 商户私钥
* @param input_charset 编码格式
* @return 签名值
*/
public static String sign(String content, String privateKey, String input_charset)
{
       try 
       {
        PKCS8EncodedKeySpec priPKCS8    = new PKCS8EncodedKeySpec( Base64.decode(privateKey) ); 
        KeyFactory keyf                 = KeyFactory.getInstance("RSA");
        PrivateKey priKey               = keyf.generatePrivate(priPKCS8);

           java.security.Signature signature = java.security.Signature
               .getInstance(SIGN_ALGORITHMS);

           signature.initSign(priKey);
           signature.update( content.getBytes(input_charset) );

           byte[] signed = signature.sign();

           return Base64.encode(signed);
       }
       catch (Exception e) 
       {
        e.printStackTrace();
       }

       return null;
   }
项目:firebase-admin-java    文件:FirebaseTokenVerifierTest.java   
private void initCrypto(String privateKey, String certificate)
    throws NoSuchAlgorithmException, InvalidKeySpecException {
  byte[] privateBytes = BaseEncoding.base64().decode(privateKey);
  KeySpec spec = new PKCS8EncodedKeySpec(privateBytes);
  String serviceAccountCertificates =
      String.format("{\"%s\" : \"%s\"}", PRIVATE_KEY_ID, certificate);

  MockHttpTransport mockTransport =
      new MockHttpTransport.Builder()
          .setLowLevelHttpResponse(
              new MockLowLevelHttpResponse().setContent(serviceAccountCertificates))
          .build();
  this.privateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
  this.verifier =
      new FirebaseTokenVerifier.Builder()
          .setClock(CLOCK)
          .setPublicKeysManager(
              new GooglePublicKeysManager.Builder(mockTransport, FACTORY)
                  .setClock(CLOCK)
                  .setPublicCertsEncodedUrl(FirebaseTokenVerifier.CLIENT_CERT_URL)
                  .build())
          .setProjectId(PROJECT_ID)
          .build();
}
项目:CrashCoin    文件:Cryptography.java   
/**
 * 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;
}
项目:AndroidOpen    文件:SignUtils.java   
/**
 * 开始签名订单
 *
 * @param content    待签名内容
 * @param privateKey 私钥
 * @return 签名后的内容
 */
public static String sign(String content, String privateKey) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);
        java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);
        signature.initSign(priKey);
        signature.update(content.getBytes(DEFAULT_CHARSET));
        byte[] signed = signature.sign();
        return Base64.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:GitHub    文件:SignUtils.java   
public static String sign(String content, String privateKey) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                Base64.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);

        signature.initSign(priKey);
        signature.update(content.getBytes(DEFAULT_CHARSET));

        byte[] signed = signature.sign();

        return Base64.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:pay-java-android    文件:SignUtils.java   
public static String sign(String content, String privateKey, boolean rsa2) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                Base64.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        java.security.Signature signature = java.security.Signature
                .getInstance(getAlgorithms(rsa2));

        signature.initSign(priKey);
        signature.update(content.getBytes(DEFAULT_CHARSET));

        byte[] signed = signature.sign();

        return Base64.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:dble    文件:DecryptUtil.java   
public static String encrypt(byte[] keyBytes, String plainText)
        throws Exception {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = factory.generatePrivate(spec);
    Cipher cipher = Cipher.getInstance("RSA");
    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;
}
项目:framework    文件:RSASign.java   
/**
 * RSA签名
 *
 * @param content       待签名数据
 * @param privateKey    商户私钥
 * @param input_charset 编码格式
 * @return 签名值
 */
public static String sign(String content, String privateKey, String input_charset) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

        signature.initSign(priKey);
        signature.update(content.getBytes(input_charset));

        byte[] signed = signature.sign();
        return new String(Base64.decodeBase64(signed));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:PicShow-zhaipin    文件:SignUtils.java   
public static String sign(String content, String privateKey, boolean rsa2) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                Base64.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        java.security.Signature signature = java.security.Signature
                .getInstance(getAlgorithms(rsa2));

        signature.initSign(priKey);
        signature.update(content.getBytes(DEFAULT_CHARSET));

        byte[] signed = signature.sign();

        return Base64.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:ipack    文件:BaseKeyFactorySpi.java   
protected KeySpec engineGetKeySpec(
    Key key,
    Class spec)
    throws InvalidKeySpecException
{
    if (spec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8"))
    {
        return new PKCS8EncodedKeySpec(key.getEncoded());
    }
    else if (spec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509"))
    {
        return new X509EncodedKeySpec(key.getEncoded());
    }

    throw new InvalidKeySpecException("not implemented yet " + key + " " + spec);
}
项目:ipack    文件:JcaPEMKeyConverter.java   
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);
    }
}
项目:ipack    文件:JcaPEMKeyConverter.java   
public PrivateKey getPrivateKey(PrivateKeyInfo privateKeyInfo)
    throws PEMException
{
    try
    {
        String algorithm =  privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm().getId();

        if (X9ObjectIdentifiers.id_ecPublicKey.getId().equals(algorithm))
        {
            algorithm = "ECDSA";
        }

        KeyFactory keyFactory = helper.createKeyFactory(algorithm);

        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded()));
    }
    catch (Exception e)
    {
        throw new PEMException("unable to convert key pair: " + e.getMessage(), e);
    }
}
项目:jdk8u-jdk    文件:DSAKeyFactory.java   
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
    try {
        if (keySpec instanceof DSAPrivateKeySpec) {
            DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
            return new DSAPrivateKey(dsaPrivKeySpec.getX(),
                                     dsaPrivKeySpec.getP(),
                                     dsaPrivKeySpec.getQ(),
                                     dsaPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DSAPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}
项目:monarch    文件:GMSEncrypt.java   
@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);
  }
}
项目:19porn    文件:Codec.java   
/**
 * 用私钥加密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] encryptByPrivateKey(byte[] data, String key)
        throws Exception {

    byte[] keyBytes = BASE64.decode(key);   // 对密钥解密

    // 取得私钥
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
    Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // 对数据加密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateKey);

    return cipher.doFinal(data);
}
项目:Spring-Boot-Server    文件:AlipayRSA.java   
/**
* RSA签名
* @param content 待签名数据
* @param privateKey 商户私钥
* @param input_charset 编码格式
* @return 签名值
*/
public static String sign(String content, String privateKey, String input_charset)
{
     try 
     {
      byte[] decode = Base64.decode(privateKey);
      PKCS8EncodedKeySpec priPKCS8   = new PKCS8EncodedKeySpec(decode );
        KeyFactory keyf= KeyFactory.getInstance("RSA");
        PrivateKey priKey= keyf.generatePrivate(priPKCS8);

         java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

         signature.initSign(priKey);
         signature.update( content.getBytes(input_charset) );

         byte[] signed = signature.sign();

         return Base64.encode(signed);
     }
     catch (Exception e) 
     {
        e.printStackTrace();
     }

     return null;
 }
项目:LuaViewPlayground    文件:VerifyUtil.java   
/**
 * read private key
 *
 * @param filename
 * @return
 */
public static PrivateKey generatePrivateKey(final String filename) {
    try {
        File f = new File(filename);
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int) f.length()];
        dis.readFully(keyBytes);
        dis.close();
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance(ALGORITHM_RSA);
        return kf.generatePrivate(spec);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
项目:JAVA-    文件:RSACoder.java   
/**
 * 签名
 * 
 * @param data 待签名数据
 * @param privateKey 私钥
 * @return byte[] 数字签名
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
    // 转换私钥材料
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // 取私钥匙对象
    PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // 实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    // 初始化Signature
    signature.initSign(priKey);
    // 更新
    signature.update(data);
    // 签名
    return signature.sign();
}
项目:RLibrary    文件:RSAUtils.java   
/**
 * <p>
 * 用私钥对信息生成数字签名
 * </p>
 *
 * @param data       已加密数据
 * @param privateKey 私钥(BASE64编码)
 * @return
 * @throws Exception
 */
public static String sign(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64Utils.decode(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateK);
    signature.update(data);
    return Base64Utils.encode(signature.sign());
}
项目:Renrentou    文件:Codec.java   
/**
 * 用私钥加密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] encryptByPrivateKey(byte[] data, String key)
        throws Exception {

    byte[] keyBytes = BASE64.decode(key);   // 对密钥解密

    // 取得私钥
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
    Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // 对数据加密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateKey);

    return cipher.doFinal(data);
}
项目:drift    文件:PemReader.java   
private static PKCS8EncodedKeySpec readPrivateKey(File keyFile, Optional<String> keyPassword)
        throws IOException, GeneralSecurityException
{
    String content = Files.toString(keyFile, US_ASCII);

    Matcher matcher = KEY_PATTERN.matcher(content);
    if (!matcher.find()) {
        throw new KeyStoreException("found no private key: " + keyFile);
    }
    byte[] encodedKey = base64Decode(matcher.group(1));

    if (!keyPassword.isPresent()) {
        return new PKCS8EncodedKeySpec(encodedKey);
    }

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encodedKey);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
    SecretKey secretKey = keyFactory.generateSecret(new PBEKeySpec(keyPassword.get().toCharArray()));

    Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
    cipher.init(DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters());

    return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
项目:openjdk-jdk10    文件:DHKeyFactory.java   
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
    throws InvalidKeySpecException
{
    try {
        if (keySpec instanceof DHPrivateKeySpec) {
            DHPrivateKeySpec dhPrivKeySpec = (DHPrivateKeySpec)keySpec;
            return new DHPrivateKey(dhPrivKeySpec.getX(),
                                    dhPrivKeySpec.getP(),
                                    dhPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DHPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification", e);
    }
}
项目:edge-jwt-sample    文件:JWTValidatorTest.java   
public PKCS8EncodedKeySpec getEncodedPrivateKeySpec(String key, String password) throws Exception {
    String privateKeyPEM = key
            .replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "")
            .replace("-----END ENCRYPTED PRIVATE KEY-----", "")
            .replaceAll("\\s", "");

    // decode to get the binary DER representation
    byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM);

    EncryptedPrivateKeyInfo epkInfo = new EncryptedPrivateKeyInfo(privateKeyDER);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
    SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

    Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, pbeKey, epkInfo.getAlgParameters());

    return epkInfo.getKeySpec(cipher);
}
项目:encrypt    文件:RSAUtil.java   
/**
 * 获取数字签名
 *
 * @param data       二进制位
 * @param privateKey 私钥(BASE64编码)
 * @return 数字签名结果字符串
 * @throws Exception 异常
 */
public static String sign(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64.decode(privateKey.getBytes(), Base64.DEFAULT);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = getKeyFactory();
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);

    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initSign(privateK);
    signature.update(data);
    return new String(Base64.encode(signature.sign(), Base64.DEFAULT));
}
项目:MPay    文件:SignUtils.java   
public static String sign(String content, String privateKey) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance(ALGORITHM, "BC");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

        signature.initSign(priKey);
        signature.update(content.getBytes(DEFAULT_CHARSET));

        byte[] signed = signature.sign();

        return Base64.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:jira-steps-plugin    文件:RsaSha1MessageSigner.java   
@Override
public String sign(HttpRequest request, HttpParameters requestParams)
    throws OAuthMessageSignerException {

  final OAuthRsaSigner signer = new OAuthRsaSigner();
  final byte[] privateBytes = Base64.decodeBase64(getConsumerSecret());
  final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateBytes);

  try {
    signer.privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);
    final String signatureBaseString = new SignatureBaseString(request, requestParams).generate();
    return signer.computeSignature(signatureBaseString);
  } catch (GeneralSecurityException e) {
    throw new OAuthMessageSignerException(e);
  }
}
项目:mumu-core    文件:RSACoder.java   
/**
 * 签名
 * 
 * @param data
 *            待签名数据
 * @param privateKey
 *            私钥
 * @return byte[] 数字签名
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
    // 转换私钥材料
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // 取私钥匙对象
    PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // 实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    // 初始化Signature
    signature.initSign(priKey);
    // 更新
    signature.update(data);
    // 签名
    return signature.sign();
}
项目:MQTT-Essentials-A-Lightweight-IoT-Protocol    文件:SecurityHelper.java   
private static PrivateKey createPrivateKeyFromPemFile(final String keyFileName) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException 
{
    // Loads a privte key from the specified key file name
    final PemReader pemReader = new PemReader(new FileReader(keyFileName));
    final PemObject pemObject = pemReader.readPemObject();
    final byte[] pemContent = pemObject.getContent();
    pemReader.close();
    final PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(pemContent);
    final KeyFactory keyFactory = getKeyFactoryInstance();
    final PrivateKey privateKey = keyFactory.generatePrivate(encodedKeySpec);
    return privateKey;
}
项目:TripBuyer    文件:SignUtils.java   
public static String sign(String content, String privateKey) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                Base64.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);

        signature.initSign(priKey);
        signature.update(content.getBytes(DEFAULT_CHARSET));

        byte[] signed = signature.sign();

        return Base64.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:JWT4B    文件:AlgorithmLinker.java   
private static PrivateKey generatePrivateKeyFromString(String key, String algorithm) {
    PrivateKey privateKey = null;
    if(key.length()>1){
        key = key.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "")
             .replaceAll("\\s+", "").replaceAll("\\r+", "").replaceAll("\\n+", "");
        byte[] keyByteArray = Base64.decode(key);
        try {
            KeyFactory kf = KeyFactory.getInstance(algorithm);
            EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyByteArray);
            privateKey = kf.generatePrivate(keySpec);
        } catch (Exception e) {
            ConsoleOut.output(e.getMessage());
        }
    }
    return privateKey;
}
项目:aaden-pay    文件:LianlianTraderRSAUtil.java   
/**
 * 签名处理
 * 
 * @param prikeyvalue
 *            :私钥
 * @param sign_str
 *            :签名源内容
 * @return
 */
public static String sign(String prikeyvalue, String sign_str) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(LianlianBase64.getBytesBASE64(prikeyvalue));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey myprikey = keyf.generatePrivate(priPKCS8);
        // 用私钥对信息生成数字签名
        java.security.Signature signet = java.security.Signature.getInstance("MD5withRSA");
        signet.initSign(myprikey);
        signet.update(sign_str.getBytes("UTF-8"));
        byte[] signed = signet.sign(); // 对信息的数字签名
        return new String(org.apache.commons.codec.binary.Base64.encodeBase64(signed));
    } catch (java.lang.Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:mumu    文件:RSACoder.java   
/**
 * 签名
 * 
 * @param data
 *            待签名数据
 * @param privateKey
 *            私钥
 * @return byte[] 数字签名
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
    // 转换私钥材料
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // 取私钥匙对象
    PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // 实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    // 初始化Signature
    signature.initSign(priKey);
    // 更新
    signature.update(data);
    // 签名
    return signature.sign();
}
项目:edge-jwt-sample    文件:JWTGeneratorTest.java   
private static String getPEMPrivateKeyFromDER(PrivateKey privateKey) {
    String begin = "-----BEGIN PRIVATE KEY-----";
    String end = "-----END PRIVATE KEY-----";
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    String key = Base64.getEncoder().encodeToString(pkcs8EncodedKeySpec.getEncoded());
    return begin + "\n" + key + "\n" + end;
}
项目:GitHub    文件:Codec.java   
/**
 * 用私钥解密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decryptByPrivateKey(byte[] data, String key)
        throws Exception {
    byte[] keyBytes = BASE64.decode(key);   // 对密钥解密

    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);   // 取得私钥
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
    Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // 对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    return cipher.doFinal(data);
}
项目:GitHub    文件:PubkeyUtils.java   
public static KeyPair recoverKeyPair(byte[] encoded) throws NoSuchAlgorithmException,
        InvalidKeySpecException {
    final String algo = getAlgorithmForOid(getOidFromPkcs8Encoded(encoded));

    final KeySpec privKeySpec = new PKCS8EncodedKeySpec(encoded);

    final KeyFactory kf = KeyFactory.getInstance(algo);
    final PrivateKey priv = kf.generatePrivate(privKeySpec);

    return new KeyPair(recoverPublicKey(kf, priv), priv);
}
项目:x-rsa    文件:XRsa.java   
public XRsa(String publicKey, String privateKey)
{
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);

        //通过X509编码的Key指令获得公钥对象
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        this.publicKey = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        //通过PKCS#8编码的Key指令获得私钥对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        this.privateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
    } catch (Exception e) {
        throw new RuntimeException("不支持的密钥", e);
    }
}
项目:nutz-pay    文件:DSA.java   
/**
 * 得到私钥
 *
 * @param key 密钥字符串(经过base64编码)
 * @throws Exception
 */
private static PrivateKey getPrivateKey(String key) {

    try {
        byte[] keyBytes;
        keyBytes = CryptoUtil.decodeBase64Byte(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return null;
    }
}
项目:edge-jwt-sample    文件:JWTGenerator.java   
public static PKCS8EncodedKeySpec getUnencodedPrivateKeySpec(String key) throws Exception {
    // strip of header, footer, newlines, whitespaces
    String privateKeyPEM = key
            .replace("-----BEGIN PRIVATE KEY-----", "")
            .replace("-----END PRIVATE KEY-----", "")
            .replaceAll("\\s", "");

    // decode to get the binary DER representation
    byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM);

    return new PKCS8EncodedKeySpec(privateKeyDER);
}