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

项目:VerifySignedJar    文件:VerfiyPKCS7Info.java   
/**
 * 从hex string 生成私钥
 * 
 * @param stringN
 * @param stringD
 * @return 构造好的私钥
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PrivateKey createPrivateKey(String stringN, String stringD)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    try {
        BigInteger N = new BigInteger(stringN, 16); // hex base
        BigInteger D = new BigInteger(stringD, 16); // hex base

        RSAPrivateKeySpec spec = new RSAPrivateKeySpec(N, D);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:mycat-src-1.6.1-RELEASE    文件:DecryptUtil.java   
public static String decrypt(PublicKey publicKey, String cipherText)
        throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    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);
}
项目:bigchaindb-java-driver    文件:RsaSha256Fulfillment.java   
public static RsaSha256Fulfillment BuildFromSecrets(String PEMEncodedPrivateKey, byte[] message, SecureRandom saltRandom) {
        ConditionType type = ConditionType.RSA_SHA256;

        try {
//            privKey = (RSAPrivateKeySpec)kf.generatePrivate(new PKCS8EncodedKeySpec(privateKey.payload));
            RSAPrivateKeySpec privKeySpec = RsaSha256Fulfillment.parsePEMEncodedPrivateKey(PEMEncodedPrivateKey);
            PrivateKey privKey = kf.generatePrivate(privKeySpec);
            Signature signatureEngine = RsaSha256Fulfillment.getSignEngine();
            signatureEngine.initSign(privKey /*, saltRandom */);
            signatureEngine.update(message);
            byte[] signature =  signatureEngine.sign();
            BigInteger modulus = privKeySpec.getModulus();
            FulfillmentPayload payload = RsaSha256Fulfillment.calculatePayload(modulus, signature);

            return new RsaSha256Fulfillment(type, payload, modulus, new SignaturePayload(signature));
        } catch (Exception e) {
            throw new RuntimeException(e.toString(), e);
        }
    }
项目:Wurst-MC-1.12    文件:Encryption.java   
private KeyPair loadRsaKeys(Path publicFile, Path privateFile)
    throws GeneralSecurityException, ReflectiveOperationException,
    IOException
{
    KeyFactory factory = KeyFactory.getInstance("RSA");

    // load public key
    PublicKey publicKey;
    try(ObjectInputStream in =
        new ObjectInputStream(Files.newInputStream(publicFile)))
    {
        publicKey = factory.generatePublic(new RSAPublicKeySpec(
            (BigInteger)in.readObject(), (BigInteger)in.readObject()));
    }

    // load private key
    PrivateKey privateKey;
    try(ObjectInputStream in =
        new ObjectInputStream(Files.newInputStream(privateFile)))
    {
        privateKey = factory.generatePrivate(new RSAPrivateKeySpec(
            (BigInteger)in.readObject(), (BigInteger)in.readObject()));
    }

    return new KeyPair(publicKey, privateKey);
}
项目:dble    文件:DecryptUtil.java   
public static String decrypt(PublicKey publicKey, String cipherText)
        throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    try {
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
    } catch (InvalidKeyException e) {
        //  IBM JDK not support Private key encryption, public key decryption
        // so fake an PrivateKey for it
        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);
}
项目:outcomes    文件:Main.java   
public static void main(String[] args) throws GeneralSecurityException, UnsupportedEncodingException {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        KeyPair kp = kpg.genKeyPair();

        KeyFactory fact = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
                RSAPublicKeySpec.class);
        RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
                RSAPrivateKeySpec.class);

        publicKey = fact.generatePublic(pub);
        privateKey = fact.generatePrivate(priv);

        String foo = rsaEncrypt("foo");

        byte[] decode = Base64.getDecoder().decode("foo");
        System.out.println(Base64.getEncoder().encodeToString(decode));

        System.out.println(rsaDecrypt(foo));

    }
项目:conscrypt    文件:OpenSSLRSAPrivateKey.java   
private static OpenSSLKey init(RSAPrivateKeySpec rsaKeySpec) throws InvalidKeySpecException {
    final BigInteger modulus = rsaKeySpec.getModulus();
    final BigInteger privateExponent = rsaKeySpec.getPrivateExponent();

    if (modulus == null) {
        throw new InvalidKeySpecException("modulus == null");
    } else if (privateExponent == null) {
        throw new InvalidKeySpecException("privateExponent == null");
    }

    try {
        return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA(
                modulus.toByteArray(),
                null,
                privateExponent.toByteArray(),
                null,
                null,
                null,
                null,
                null));
    } catch (Exception e) {
        throw new InvalidKeySpecException(e);
    }
}
项目:conscrypt    文件:OpenSSLRSAKeyFactory.java   
@Override
protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
    if (keySpec == null) {
        throw new InvalidKeySpecException("keySpec == null");
    }

    if (keySpec instanceof RSAPrivateCrtKeySpec) {
        return new OpenSSLRSAPrivateCrtKey((RSAPrivateCrtKeySpec) keySpec);
    } else if (keySpec instanceof RSAPrivateKeySpec) {
        return new OpenSSLRSAPrivateKey((RSAPrivateKeySpec) keySpec);
    } else if (keySpec instanceof PKCS8EncodedKeySpec) {
        return OpenSSLKey.getPrivateKey((PKCS8EncodedKeySpec) keySpec,
                NativeConstants.EVP_PKEY_RSA);
    }
    throw new InvalidKeySpecException("Must use RSAPublicKeySpec or PKCS8EncodedKeySpec; was "
            + keySpec.getClass().getName());
}
项目:UnderBar    文件:RSA.java   
static PrivateKey sshPrivateKey(String key){
    StringBuilder bob = new StringBuilder();
    filter(list(key.split("\n")), (line) -> !(line.contains("-") || line.contains(":"))).forEach(
            (line) -> {
                bob.append(line);
                bob.append("\n");
    });

    byte[] bytes = Base64.getDecoder().decode(bob.toString().replace("\n", ""));

    DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));

    dieIf(rethrow(() -> in.read()) != 48, () -> "Unexpected Block Size in part 1");
    dieIf(rethrow(() -> in.read()) != 130, () -> "Unexpected Block Size in part 2");
    rethrow(() -> in.skipBytes(5));

    BigInteger modulo = readBigInteger(in);
    readBigInteger(in);
    BigInteger exponent = readBigInteger(in);

    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulo, exponent);
    return rethrow(() -> KeyFactory.getInstance("RSA").generatePrivate(rsaPrivateKeySpec));
}
项目:MultimediaDesktop    文件:ConfigTools.java   
public static String decrypt(PublicKey publicKey, String cipherText)
        throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    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);
}
项目:jaramiko    文件:CraiJCE.java   
public byte[] sign(byte[] b, int off, int len) throws CraiException {
    try {
        // HOLY FREAKING MOTHER OF A GOAT SCROAT WHY DOES JAVA MAKE THIS
        // SO PAINFUL?!?!?!
        Signature s = Signature.getInstance("SHA1withRSA");
        KeyFactory keyFac = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFac.generatePrivate(new RSAPrivateKeySpec(
                mN, mD));
        s.initSign(key, ((JCERandom) mCraiRandom).mRandom);
        s.update(b, off, len);
        return s.sign();
    } catch (Exception e) {
        // JCE can throw weird exceptions at every stage :/
        throw new CraiException("error performing RSA signature: " + e);
    }
}
项目:sc2gears    文件:RsaKeyPairGen.java   
public static void main( final String[] args ) throws Exception {
    final KeyPairGenerator kpGen = KeyPairGenerator.getInstance( "RSA" );
    kpGen.initialize( KEY_SIZE_BITS );
    final KeyPair kp = kpGen.generateKeyPair();

    final PublicKey  pubKey  = kp.getPublic();
    final PrivateKey privKey = kp.getPrivate();

    if ( DEBUG ) {
        System.out.println( pubKey .getAlgorithm() + " " + pubKey .getFormat() + " " + pubKey .getEncoded().length );
        System.out.println( privKey.getAlgorithm() + " " + privKey.getFormat() + " " + privKey.getEncoded().length );
    }

    final KeyFactory kf = KeyFactory.getInstance( "RSA" );
    final RSAPublicKeySpec  pubKeySpec  = kf.getKeySpec( pubKey , RSAPublicKeySpec .class );
    final RSAPrivateKeySpec privKeySpec = kf.getKeySpec( privKey, RSAPrivateKeySpec.class );

    if ( DEBUG ) {
        System.out.println( pubKeySpec .getModulus() + " " + pubKeySpec .getPublicExponent() );
        System.out.println( privKeySpec.getModulus() + " " + privKeySpec.getPrivateExponent() );
    }

    saveKey( pubKeySpec .getModulus(), pubKeySpec .getPublicExponent (), "w:/pubkey.rsa"  );
    saveKey( privKeySpec.getModulus(), privKeySpec.getPrivateExponent(), "w:/privkey.rsa" );
}
项目:sc2gears    文件:PrivKeyEncrypt.java   
public static void main( final String[] args ) throws Exception {
    final KeyFactory kf = KeyFactory.getInstance( "RSA" );

    final BigInteger[] modExp = loadKey( "w:/privkey.rsa" );
    final PrivateKey privKey = kf.generatePrivate( new RSAPrivateKeySpec( modExp[ 0 ], modExp[ 1 ] ) );

    final Cipher cipher = Cipher.getInstance( "RSA" );
    cipher.init( Cipher.ENCRYPT_MODE, privKey );
    final byte[] encrypted = cipher.doFinal( DOCUMENT.getBytes( "UTF-8") );

    System.out.println( "Successful encryption." );

    try ( final FileOutputStream out = new FileOutputStream( "w:/encrypted.dat" ) ) {
        out.write( encrypted );
    }
}
项目:GeneralUtils    文件:RSAHelper.java   
/**
 * 加载 PKCS#1 编码的 pem 格式私钥
 * 
 * @param privateKeyStr 私钥
 * @throws Exception
 */
public void loadPrivateKeyPEMPKCS1(String privateKeyStr) throws Exception {
    try {
        byte[] e = Base64.decode(privateKeyStr);
        // 读取 PKCS#1的私钥
        RSAPrivateKeyStructure asn1PrivateKey = new RSAPrivateKeyStructure(
                                                                           (ASN1Sequence) ASN1Sequence.fromByteArray(e));
        RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(asn1PrivateKey.getModulus(),
                                                                    asn1PrivateKey.getPrivateExponent());
        // 实例化KeyFactory对象,并指定 RSA 算法
        KeyFactory keyFactory = KeyFactory.getInstance(SIGN_ALGORITHMS);
        // 获得 PrivateKey 对象
        this.privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec);
    } catch (NoSuchAlgorithmException var6) {
        throw new Exception("无此算法");
    } catch (InvalidKeySpecException var7) {
        throw new Exception("私钥非法");
    } catch (IOException var8) {
        throw new Exception("私钥数据内容读取错误");
    } catch (NullPointerException var9) {
        throw new Exception("私钥数据为空");
    }
}
项目:ssh-agent-proxy    文件:TraditionalKeyParser.java   
public static RSAPrivateKeySpec parsePemPrivateKey(String pemPrivateKey)
    throws InvalidKeyException {
  pemPrivateKey = pemPrivateKey.replace("\n", "");
  Matcher matcher = PRIVATE_KEY_PATTERN.matcher(pemPrivateKey);
  if (!matcher.matches()) {
    throw new InvalidKeyException();
  }
  String pemKey = matcher.group(1);
  BaseEncoding encoding = BaseEncoding.base64();
  byte[] derKey = encoding.decode(pemKey);
  List<byte[]> fields;
  try {
    fields = parsePrivateKeyAsn1(ByteBuffer.wrap(derKey));
  } catch (IllegalArgumentException e) {
    throw new InvalidKeyException(e);
  }
  BigInteger mod = new BigInteger(fields.get(1));
  BigInteger exp = new BigInteger(fields.get(3));
  return new RSAPrivateKeySpec(mod, exp);
}
项目:In-the-Box-Fork    文件:RSAMultiPrimePrivateCrtKeySpecTest.java   
/**
 * Test #12 for
 * <code>RSAMultiPrimePrivateCrtKeySpec(BigInteger modulus,
 *                                      BigInteger publicExponent,
 *                                      BigInteger privateExponent,
 *                                      BigInteger primeP,
 *                                      BigInteger primeQ,
 *                                      BigInteger primeExponentP,
 *                                      BigInteger primeExponentQ,
 *                                      BigInteger crtCoefficient,
 *                                      RSAOtherPrimeInfo[] otherPrimeInfo)
 * </code> ctor<br>
 * Assertion: constructs <code>RSAMultiPrimePrivateCrtKeySpec</code>
 * object using valid parameters. Constructed object must be
 * instance of RSAPrivateKeySpec.
 */
@TestTargetNew(
    level = TestLevel.PARTIAL_COMPLETE,
    notes = "Verifies constructor using valid parameters. Constructed object must be instance of RSAPrivateKeySpec.",
    method = "RSAMultiPrimePrivateCrtKeySpec",
    args = {java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.security.spec.RSAOtherPrimeInfo[].class}
)
public final void testRSAMultiPrimePrivateCrtKeySpec12() {
    KeySpec ks = new RSAMultiPrimePrivateCrtKeySpec(
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            opi);
    assertTrue(ks instanceof RSAPrivateKeySpec);
}
项目:In-the-Box-Fork    文件:RSAPrivateCrtKeySpecTest.java   
/**
 * Test #2 for <code>RSAPrivateCrtKeySpec</code> constructor
 * Assertion: Constructs <code>RSAPrivateCrtKeySpec</code>
 * object using valid parameters
 */
@TestTargetNew(
    level = TestLevel.PARTIAL_COMPLETE,
    notes = "Verifies constructor with valid parameters.",
    method = "RSAPrivateCrtKeySpec",
    args = {java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class, java.math.BigInteger.class}
)
public final void testRSAPrivateCrtKeySpec02() {
    KeySpec ks = new RSAPrivateCrtKeySpec(
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE);
    assertTrue(ks instanceof RSAPrivateKeySpec);
}
项目:crtauth-java    文件:TraditionalKeyParser.java   
public static RSAPrivateKeySpec parsePemPrivateKey(String pemPrivateKey)
    throws InvalidKeyException {
  pemPrivateKey = pemPrivateKey.replace("\n", "");
  Matcher matcher = PRIVATE_KEY_PATTERN.matcher(pemPrivateKey);
  if (!matcher.matches()) {
    throw new InvalidKeyException();
  }
  String pemKey = matcher.group(1);
  BaseEncoding encoding = BaseEncoding.base64();
  byte[] derKey = encoding.decode(pemKey);
  List<byte[]> fields;
  try {
    fields = parsePrivateKeyASN1(ByteBuffer.wrap(derKey));
  } catch (IllegalArgumentException e) {
    throw new InvalidKeyException(e);
  }
  BigInteger mod = new BigInteger(fields.get(1));
  BigInteger exp = new BigInteger(fields.get(3));
  return new RSAPrivateKeySpec(mod, exp);
}
项目:crtauth-java    文件:CrtAuthServerTest.java   
@Before
public void setup() throws Exception {
  keyProvider = new InMemoryKeyProvider();
  KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  RSAPublicKeySpec noaPublicKeySpec = TraditionalKeyParser.parsePemPublicKey(NOA_PUBLIC_KEY);
  RSAPublicKey noaPublicKey = (RSAPublicKey) keyFactory.generatePublic(noaPublicKeySpec);
  keyProvider.putKey("noa", noaPublicKey);
  RSAPublicKeySpec publicKeySpec = TraditionalKeyParser.parsePemPublicKey(PUBLIC_KEY);
  RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
  keyProvider.putKey("test", publicKey);
  crtAuthServer = new CrtAuthServer.Builder()
      .setServerName(SERVER_NAME)
      .setSecret("server_secret".getBytes())
      .setKeyProvider(keyProvider)
      .build();
  RSAPrivateKeySpec privateKeySpec = TraditionalKeyParser.parsePemPrivateKey(PRIVATE_KEY);
  PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
  Signer signer = new SingleKeySigner(privateKey);
  crtAuthClient = new CrtAuthClient(signer, SERVER_NAME);
}
项目:tor-research-framework    文件:TorCrypto.java   
/**
 * Parses a public key encoded as ASN.1
 *
 * @param rsapublickey ASN.1 Encoded public key
 * @return PublicKey
 */

public static RSAPrivateKey asn1GetPrivateKey(byte[] rsapkbuf) {
    ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(rsapkbuf));
    try {
        DLSequence obj = (DLSequence) bIn.readObject();
        ASN1Integer mod = (ASN1Integer) obj.getObjectAt(1);
        ASN1Integer pubExp = (ASN1Integer) obj.getObjectAt(2);
        ASN1Integer privExp = (ASN1Integer) obj.getObjectAt(3);

        RSAPrivateKey privKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(mod.getValue(), privExp.getValue()));
        return privKey;
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();
    }

    return null;
}
项目:dxcrypto    文件:CryptoRSAEngineFactory.java   
@Override
public EncryptionEngine newEngine(RSAKeyParams publicKey, RSAKeyParams privateKey) {
    try {
        String shortAlgorithmName = algorithmName.contains("/") ? algorithmName.substring(0, algorithmName.indexOf("/")) : algorithmName;
        KeyFactory keyFactory = KeyFactory.getInstance(shortAlgorithmName);
        Key pubKey = null, privKey = null;
        if (publicKey != null) {
            RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent());
            pubKey = keyFactory.generatePublic(pubKeySpec);
        }
        if (privateKey != null) {
            RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(privateKey.getModulus(), privateKey.getExponent());
            privKey = keyFactory.generatePrivate(privKeySpec);
        }
        return new CryptoAsymmetricEngine(algorithmName, pubKey, privKey);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new EncryptionException("Unable to retrieve RSA public key", e);
    }
}
项目:OpenTools    文件:RSAUtils.java   
public static String decrypt(PublicKey publicKey, String cipherText) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    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);
}
项目:2FactorWallet    文件:ProtocolServer.java   
private SSLContext createServerSSLContext() {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        java.security.cert.Certificate cert = generateCertificate();
        RSAKeyParameters privateKey = (RSAKeyParameters) keyPair.getPrivate();
        RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateKey.getModulus(), privateKey.getExponent());
        PrivateKey jPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(privateKeySpec);
        keyStore.setKeyEntry("myCert", jPrivateKey, "aaa".toCharArray(), new java.security.cert.Certificate[]{cert});
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "aaa".toCharArray());
        SSLContext serverContext = SSLContext.getInstance("TLS");
        serverContext.init(kmf.getKeyManagers(), null, null);
        return serverContext;
    } catch (Exception e) {
        throw new Error("Failed to initialize the server-side SSLContext", e);
    }
}
项目:heisenberg    文件:KeyPairGen.java   
public static String decrypt(PublicKey publicKey, String cipherText)
  throws Exception
{
  Cipher cipher = Cipher.getInstance("RSA");
  try {
    cipher.init(2, publicKey);
  }
  catch (InvalidKeyException e)
  {
    RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
    RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
    Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
    cipher = Cipher.getInstance("RSA");
    cipher.init(2, fakePrivateKey);
  }

  if ((cipherText == null) || (cipherText.length() == 0)) {
    return cipherText;
  }

  byte[] cipherBytes = Base64.decodeBase64(cipherText);
  byte[] plainBytes = cipher.doFinal(cipherBytes);

  return new String(plainBytes);
}
项目:STAR-Vote    文件:RSACrypto.java   
/**
 * Create an RSA digital signature.
 * 
 * @param data      Sign this expression's verbatim form.
 * @param key       Use this key to create the signature.
 * @return          The signature data.
 *
 * @throws AuditoriumCryptoException Thrown if there is a problem with signing the data
 */
public Signature sign(ASExpression data, Key key) throws AuditoriumCryptoException {
    try {
        /* Build a key using RSA */
        KeyFactory factory = KeyFactory.getInstance("RSA");
        java.security.Signature sig = java.security.Signature.getInstance("SHA1withRSA");
        PrivateKey privatekey = factory.generatePrivate(new RSAPrivateKeySpec(key.getMod(), key.getKey()));

        /* Initialize the signer */
        sig.initSign(privatekey);
        sig.update(data.toVerbatim());

        /* Return a new Signature object with the signed data and signature from the key*/
        return new Signature(key.getId(), StringExpression.makeString(sig.sign()), data);
    }
    catch (Exception e) {
        throw new AuditoriumCryptoException("sign", e);
    }
}
项目:TIIEHenry-Android-SDK    文件:RSAUtils.java   
/**
 * 生成私钥
 *
 * @param modulus
 * @param privateExponent
 * @return RSAPrivateKey
 */
private static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) {
    try {
        KeyFactory keyFac = KeyFactory.getInstance(KEY_ALGORITHM);
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(1, modulus), new BigInteger(1, privateExponent));
        return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
    } catch (Exception e) {
        throw new RuntimeException("Error when generate rsaPrivateKey, errmsg: "
                + e.getMessage(), e);
    }
}
项目:ipack    文件:KeyFactorySpi.java   
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof PKCS8EncodedKeySpec)
    {
        try
        {
            return generatePrivate(PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()));
        }
        catch (Exception e)
        {
            //
            // in case it's just a RSAPrivateKey object... -- openSSL produces these
            //
            try
            {
                return new BCRSAPrivateCrtKey(
                    RSAPrivateKey.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()));
            }
            catch (Exception ex)
            {
                throw new ExtendedInvalidKeySpecException("unable to process key spec: " + e.toString(), e);
            }
        }
    }
    else if (keySpec instanceof RSAPrivateCrtKeySpec)
    {
        return new BCRSAPrivateCrtKey((RSAPrivateCrtKeySpec)keySpec);
    }
    else if (keySpec instanceof RSAPrivateKeySpec)
    {
        return new BCRSAPrivateKey((RSAPrivateKeySpec)keySpec);
    }

    throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
项目:utilsLibrary    文件:RSAUtils.java   
private static PrivateKey getPrivateKey(String modulus,
                                        String privateExponent) throws NoSuchAlgorithmException,
        InvalidKeySpecException {
    BigInteger bigIntModulus = new BigInteger(modulus);
    BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
    RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(bigIntModulus,
            bigIntPrivateExponent);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(keySpec);
}
项目:FirefoxData-android    文件:RSACryptoImplementation.java   
public static SigningPrivateKey createPrivateKey(BigInteger n, BigInteger d) throws NoSuchAlgorithmException, InvalidKeySpecException {
  if (n == null) {
    throw new IllegalArgumentException("n must not be null");
  }
  if (d == null) {
    throw new IllegalArgumentException("d must not be null");
  }
  KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  KeySpec keySpec = new RSAPrivateKeySpec(n, d);
  RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
  return new RSASigningPrivateKey(privateKey);
}
项目:GroupControlDroidClient    文件:RSAUtil.java   
/**
 * 使用模和指数生成RSA私钥
 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
 * /None/NoPadding】
 * 
 * @param modulus
 *            模
 * @param exponent
 *            指数
 * @return
 */
public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
    try {
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
项目:Android_Code_Arbiter    文件:ConstantPasswords.java   
public void bad10() throws Exception {
    BigInteger bigInteger = new BigInteger("12345", 5);
    new DSAPrivateKeySpec(bigInteger, null, null, null);
    new DSAPublicKeySpec(bigInteger, null, bigInteger, null); // report once
    new DHPrivateKeySpec(bigInteger, null, null);
    new DHPublicKeySpec(bigInteger, null, null);
    new ECPrivateKeySpec(bigInteger, null);
    new RSAPrivateKeySpec(bigInteger, null);
    new RSAMultiPrimePrivateCrtKeySpec(bigInteger, null, null, null, null, null, null, null, null);
    new RSAPrivateCrtKeySpec(bigInteger, null, null, null, null, null, null, null);
    new RSAPublicKeySpec(bigInteger, null);
    new DSAPublicKeyImpl(bigInteger, null, null, null);
}
项目:silvertunnel-ng    文件:Encryption.java   
/**
 * Create a key based on the parameters.
 *
 * @param modulus
 * @param privateExponent
 * @return the key
 */
public static RSAPrivateKey getRSAPrivateKey(final BigInteger modulus, final BigInteger privateExponent) {
    try {
        return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
    } catch (final GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
项目:mpush    文件:RSAUtils.java   
/**
 * 使用模和指数生成RSA私钥
 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,
 * 不同JDK默认的补位方式可能不同,如Android默认是RSA
 * /None/NoPadding】
 *
 * @param modulus  模
 * @param exponent 指数
 * @return 私钥
 */
public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
    try {
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (Exception e) {
        LOGGER.error("getPrivateKey ex modulus={}, exponent={}", modulus, exponent, e);
        throw new CryptoException("Get PrivateKey ex", e);
    }
}
项目:TLS-Attacker    文件:CertificateUtils.java   
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;
}
项目:scaffold    文件:RSAHandler.java   
/**
 * 使用模和指数生成RSA私钥
 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
 * /None/NoPadding】
 *
 * @param modulus  模
 * @param exponent 指数
 * @return RSAPrivateKey
 */
public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
    try {
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
项目:mpush-client-java    文件:RSAUtils.java   
/**
 * 使用模和指数生成RSA私钥
 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,
 * 不同JDK默认的补位方式可能不同,如Android默认是RSA
 * /None/NoPadding】
 *
 * @param modulus modulus  模
 * @param exponent exponent 指数
 * @return xxx
 */
public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
    try {
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (Exception e) {
        //LOGGER.error("getPrivateKey ex modulus={}, exponent={}", modulus, exponent, e);
        return null;
    }
}
项目:L2crypt    文件:L2Ver41xInputStream.java   
public RSAInputStream(InputStream input, BigInteger modulus, BigInteger exponent) throws CryptoException {
    this.input = new DataInputStream(input);

    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(modulus, exponent);
        cipher = Cipher.getInstance("RSA/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, keyFactory.generatePrivate(keySpec));
    } catch (GeneralSecurityException e) {
        throw new CryptoException(e);
    }
}
项目:Jose4j    文件:RsaKeyUtil.java   
public RSAPrivateKey getRsaPrivateKey(RSAPrivateKeySpec keySpec) throws JoseException
{
    try
    {
        PrivateKey privateKey = getKeyFactory().generatePrivate(keySpec);
        return (RSAPrivateKey) privateKey;
    }
    catch (InvalidKeySpecException e)
    {
        throw new JoseException("Invalid key spec: " + e, e);
    }
}
项目:Android-EDP-SDK    文件:RSAUtils.java   
/**
 * 使用模和指数生成RSA私钥
 * 注意:【此代码使用的补位方式为,为RSA/ECB/PKCS1Padding】
 *
 * @param modulus  模
 * @param exponent 指数
 * @return
 */
public static RSAPrivateKey getPrivateKey(BigInteger modulus, BigInteger exponent) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(modulus, exponent);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
项目:Aki-SSL    文件:KeyFactorySpi.java   
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof PKCS8EncodedKeySpec)
    {
        try
        {
            return generatePrivate(PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()));
        }
        catch (Exception e)
        {
            //
            // in case it's just a RSAPrivateKey object... -- openSSL produces these
            //
            try
            {
                return new BCRSAPrivateCrtKey(
                    RSAPrivateKey.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()));
            }
            catch (Exception ex)
            {
                throw new ExtendedInvalidKeySpecException("unable to process key spec: " + e.toString(), e);
            }
        }
    }
    else if (keySpec instanceof RSAPrivateCrtKeySpec)
    {
        return new BCRSAPrivateCrtKey((RSAPrivateCrtKeySpec)keySpec);
    }
    else if (keySpec instanceof RSAPrivateKeySpec)
    {
        return new BCRSAPrivateKey((RSAPrivateKeySpec)keySpec);
    }

    throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}