Java Code Examples for java.security.spec.RSAPrivateKeySpec

The following are top voted examples for showing how to use java.security.spec.RSAPrivateKeySpec. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: VerifySignedJar   File: VerfiyPKCS7Info.java   View source code 6 votes vote down vote up
/**
 * 从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;
}
 
Example 2
Project: mycat-src-1.6.1-RELEASE   File: DecryptUtil.java   View source code 6 votes vote down vote up
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);
}
 
Example 3
Project: bigchaindb-java-driver   File: RsaSha256Fulfillment.java   View source code 6 votes vote down vote up
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);
        }
    }
 
Example 4
Project: Wurst-MC-1.12   File: Encryption.java   View source code 6 votes vote down vote up
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);
}
 
Example 5
Project: dble   File: DecryptUtil.java   View source code 6 votes vote down vote up
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);
}
 
Example 6
Project: outcomes   File: Main.java   View source code 6 votes vote down vote up
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));

    }
 
Example 7
Project: conscrypt   File: OpenSSLRSAPrivateKey.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 8
Project: conscrypt   File: OpenSSLRSAKeyFactory.java   View source code 6 votes vote down vote up
@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());
}
 
Example 9
Project: UnderBar   File: RSA.java   View source code 6 votes vote down vote up
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));
}
 
Example 10
Project: MultimediaDesktop   File: ConfigTools.java   View source code 6 votes vote down vote up
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);
}
 
Example 11
Project: jaramiko   File: CraiJCE.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 12
Project: sc2gears   File: RsaKeyPairGen.java   View source code 6 votes vote down vote up
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" );
}
 
Example 13
Project: sc2gears   File: PrivKeyEncrypt.java   View source code 6 votes vote down vote up
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 );
	}
}
 
Example 14
Project: GeneralUtils   File: RSAHelper.java   View source code 6 votes vote down vote up
/**
 * 加载 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("私钥数据为空");
    }
}
 
Example 15
Project: ssh-agent-proxy   File: TraditionalKeyParser.java   View source code 6 votes vote down vote up
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);
}
 
Example 16
Project: In-the-Box-Fork   File: RSAMultiPrimePrivateCrtKeySpecTest.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 17
Project: In-the-Box-Fork   File: RSAPrivateCrtKeySpecTest.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 18
Project: crtauth-java   File: TraditionalKeyParser.java   View source code 6 votes vote down vote up
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);
}
 
Example 19
Project: crtauth-java   File: CrtAuthServerTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 20
Project: tor-research-framework   File: TorCrypto.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 21
Project: dxcrypto   File: CryptoRSAEngineFactory.java   View source code 6 votes vote down vote up
@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);
    }
}
 
Example 22
Project: OpenTools   File: RSAUtils.java   View source code 6 votes vote down vote up
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);
}
 
Example 23
Project: 2FactorWallet   File: ProtocolServer.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 24
Project: heisenberg   File: KeyPairGen.java   View source code 6 votes vote down vote up
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);
}
 
Example 25
Project: STAR-Vote   File: RSACrypto.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 26
Project: TIIEHenry-Android-SDK   File: RSAUtils.java   View source code 5 votes vote down vote up
/**
 * 生成私钥
 *
 * @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);
    }
}
 
Example 27
Project: ipack   File: KeyFactorySpi.java   View source code 5 votes vote down vote up
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());
}
 
Example 28
Project: utilsLibrary   File: RSAUtils.java   View source code 5 votes vote down vote up
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);
}
 
Example 29
Project: FirefoxData-android   File: RSACryptoImplementation.java   View source code 5 votes vote down vote up
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);
}
 
Example 30
Project: GroupControlDroidClient   File: RSAUtil.java   View source code 5 votes vote down vote up
/**
 * 使用模和指数生成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;
	}
}
 
Example 31
Project: Android_Code_Arbiter   File: ConstantPasswords.java   View source code 5 votes vote down vote up
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);
}
 
Example 32
Project: silvertunnel-ng   File: Encryption.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 33
Project: mpush   File: RSAUtils.java   View source code 5 votes vote down vote up
/**
 * 使用模和指数生成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);
    }
}
 
Example 34
Project: TLS-Attacker   File: CertificateUtils.java   View source code 5 votes vote down vote up
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;
}
 
Example 35
Project: scaffold   File: RSAHandler.java   View source code 5 votes vote down vote up
/**
 * 使用模和指数生成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;
    }
}
 
Example 36
Project: mpush-client-java   File: RSAUtils.java   View source code 5 votes vote down vote up
/**
 * 使用模和指数生成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;
    }
}
 
Example 37
Project: L2crypt   File: L2Ver41xInputStream.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 38
Project: Jose4j   File: RsaKeyUtil.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 39
Project: Android-EDP-SDK   File: RSAUtils.java   View source code 5 votes vote down vote up
/**
 * 使用模和指数生成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;
    }
}
 
Example 40
Project: Aki-SSL   File: KeyFactorySpi.java   View source code 5 votes vote down vote up
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());
}