Java 类org.bouncycastle.asn1.pkcs.RSAPublicKey 实例源码

项目:gwt-crypto    文件:CMSTestUtil.java   
public static X509CertificateHolder makeV1Certificate(AsymmetricCipherKeyPair subKP, String _subDN, AsymmetricCipherKeyPair issKP, String _issDN)
    throws IOException, OperatorCreationException
{
    RSAKeyParameters lwPubKey = (RSAKeyParameters)subKP.getPublic();

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(
        new X500Name(_issDN),
        allocateSerialNumber(),
        new Date(System.currentTimeMillis()),
        new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
        new X500Name(_subDN),
        new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPublicKey(lwPubKey.getModulus(), lwPubKey.getExponent()))
    );

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build((AsymmetricKeyParameter)issKP.getPrivate());


    return v1CertGen.build(sigGen);
}
项目:gwt-crypto    文件:CMSTestUtil.java   
public static X509CertificateHolder makeCertificate(AsymmetricCipherKeyPair subKP, String _subDN, AsymmetricCipherKeyPair issKP, String _issDN, boolean _ca)
    throws IOException, OperatorCreationException
{
    RSAKeyParameters lwPubKey = (RSAKeyParameters)subKP.getPublic();

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
        new X500Name(_issDN),
        allocateSerialNumber(),
        new Date(System.currentTimeMillis()),
        new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
        new X500Name(_subDN),
        new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPublicKey(lwPubKey.getModulus(), lwPubKey.getExponent()))
    );

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build((AsymmetricKeyParameter)issKP.getPrivate());

    v3CertGen.addExtension(
        X509Extension.basicConstraints,
        false,
        new BasicConstraints(_ca));

    return v3CertGen.build(sigGen);
}
项目:kisso    文件:RsaKeyHelper.java   
public static java.security.interfaces.RSAPublicKey parsePublicKey(String key) {
    Matcher m = SSH_PUB_KEY.matcher(key);
    if (m.matches()) {
        String alg = m.group(1);
        String encKey = m.group(2);
        if (!"rsa".equalsIgnoreCase(alg)) {
            throw new IllegalArgumentException("Only RSA is currently supported, but algorithm was " + alg);
        } else {
            return parseSSHPublicKey(encKey);
        }
    } else if (!key.startsWith(BEGIN)) {
        return parseSSHPublicKey(key);
    } else {
        KeyPair kp = parseKeyPair(key);
        if (kp.getPublic() == null) {
            throw new IllegalArgumentException("Key data does not contain a public key");
        } else {
            return (java.security.interfaces.RSAPublicKey) kp.getPublic();
        }
    }
}
项目:kisso    文件:RsaKeyHelper.java   
private static java.security.interfaces.RSAPublicKey parseSSHPublicKey(String encKey) {
    byte[] PREFIX = new byte[]{0, 0, 0, 7, 115, 115, 104, 45, 114, 115, 97};
    ByteArrayInputStream in = new ByteArrayInputStream(Codecs.b64Decode(Codecs.utf8Encode(encKey)));
    byte[] prefix = new byte[11];

    try {
        if (in.read(prefix) == 11 && Arrays.equals(PREFIX, prefix)) {
            BigInteger e = new BigInteger(readBigInteger(in));
            BigInteger n = new BigInteger(readBigInteger(in));
            return createPublicKey(n, e);
        } else {
            throw new IllegalArgumentException("SSH key prefix not found");
        }
    } catch (IOException var6) {
        throw new RuntimeException(var6);
    }
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * makes RSA public key from bin byte array.
 *
 * @param b byte array that contains the key
 * @return
 * @see JCERSAPublicKey
 */
public static RSAPublicKey extractBinaryRSAKey(final byte[] b) {
    RSAPublicKey theKey;

    try {
        final ASN1InputStream ais = new ASN1InputStream(b);
        final Object asnObject = ais.readObject();
        final ASN1Sequence sequence = (ASN1Sequence) asnObject;
        final RSAPublicKeyStructure tempKey = new RSAPublicKeyStructure(sequence);
        theKey = getRSAPublicKey(tempKey.getModulus(), tempKey.getPublicExponent());
        ais.close();
    } catch (final IOException e) {
        logger.warn("Caught exception:" + e.getMessage());
        theKey = null;
    }

    return theKey;
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * Create a fresh RSA key pair.
 *
 * @return a new RSAKeyPair
 */
public static RSAKeyPair createNewRSAKeyPair() {
    try {
        // Generate a 1024-bit RSA key pair
        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(KEY_STRENGTH);
        final KeyPair keypair = keyGen.genKeyPair();
        final RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keypair.getPrivate();
        final RSAPublicKey publicKey = (RSAPublicKey) keypair.getPublic();

        return new RSAKeyPair(publicKey, privateKey);

    } catch (final NoSuchAlgorithmException e) {
        logger.error("Could not create new key pair", e);
        throw new RuntimeException(e);
    }
}
项目:subshare    文件:CryptoRegistry.java   
/**
 * Encode (serialise) a public key in order to store it or transport it over a network.
 * @param publicKey the public key to be encoded; must not be <code>null</code>.
 * @return the encoded (serialised) form of the public key. Can be passed to {@link #decodePublicKey(byte[])} to
 * reverse this method.
 * @see #decodePublicKey(byte[])
 * @see #encodePrivateKey(CipherParameters)
 */
public byte[] encodePublicKey(final CipherParameters publicKey)
{
    if (publicKey == null)
        throw new IllegalArgumentException("publicKey == null");

    // TODO use a class-based map or similar registry!
    try {
        if (publicKey instanceof RSAKeyParameters) {
            final RSAKeyParameters rsaPublicKey = (RSAKeyParameters) publicKey;

            final SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE),
                    new RSAPublicKey(rsaPublicKey.getModulus(), rsaPublicKey.getExponent()).toASN1Primitive()
                    );
            return info.getEncoded();
        }
    } catch (final IOException x) {
        throw new RuntimeException(x);
    }

    throw new UnsupportedOperationException("publicKey.class=\"" + publicKey.getClass().getName() + "\" not yet supported!");
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * makes RSA public key from bin byte array.
 *
 * @param b byte array that contains the key
 * @return
 * @see JCERSAPublicKey
 */
public static RSAPublicKey extractBinaryRSAKey(final byte[] b) {
    RSAPublicKey theKey;

    try {
        final ASN1InputStream ais = new ASN1InputStream(b);
        final Object asnObject = ais.readObject();
        final ASN1Sequence sequence = (ASN1Sequence) asnObject;
        final RSAPublicKeyStructure tempKey = new RSAPublicKeyStructure(sequence);
        theKey = getRSAPublicKey(tempKey.getModulus(), tempKey.getPublicExponent());
        ais.close();
    } catch (final IOException e) {
        logger.warn("Caught exception:" + e.getMessage());
        theKey = null;
    }

    return theKey;
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * Create a fresh RSA key pair.
 *
 * @return a new RSAKeyPair
 */
public static RSAKeyPair createNewRSAKeyPair() {
    try {
        // Generate a 1024-bit RSA key pair
        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(KEY_STRENGTH);
        final KeyPair keypair = keyGen.genKeyPair();
        final RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keypair.getPrivate();
        final RSAPublicKey publicKey = (RSAPublicKey) keypair.getPublic();

        return new RSAKeyPair(publicKey, privateKey);

    } catch (final NoSuchAlgorithmException e) {
        logger.error("Could not create new key pair", e);
        throw new RuntimeException(e);
    }
}
项目:irma_future_id    文件:CMSTestUtil.java   
public static X509CertificateHolder makeV1Certificate(AsymmetricCipherKeyPair subKP, String _subDN, AsymmetricCipherKeyPair issKP, String _issDN)
    throws IOException, OperatorCreationException
{
    RSAKeyParameters lwPubKey = (RSAKeyParameters)subKP.getPublic();

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(
        new X500Name(_issDN),
        allocateSerialNumber(),
        new Date(System.currentTimeMillis()),
        new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
        new X500Name(_subDN),
        new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPublicKey(lwPubKey.getModulus(), lwPubKey.getExponent()))
    );

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build((AsymmetricKeyParameter)issKP.getPrivate());


    return v1CertGen.build(sigGen);
}
项目:irma_future_id    文件:CMSTestUtil.java   
public static X509CertificateHolder makeCertificate(AsymmetricCipherKeyPair subKP, String _subDN, AsymmetricCipherKeyPair issKP, String _issDN, boolean _ca)
    throws IOException, OperatorCreationException
{
    RSAKeyParameters lwPubKey = (RSAKeyParameters)subKP.getPublic();

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
        new X500Name(_issDN),
        allocateSerialNumber(),
        new Date(System.currentTimeMillis()),
        new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
        new X500Name(_subDN),
        new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPublicKey(lwPubKey.getModulus(), lwPubKey.getExponent()))
    );

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build((AsymmetricKeyParameter)issKP.getPrivate());

    v3CertGen.addExtension(
        X509Extension.basicConstraints,
        false,
        new BasicConstraints(_ca));

    return v3CertGen.build(sigGen);
}
项目:bc-java    文件:CMSTestUtil.java   
public static X509CertificateHolder makeV1Certificate(AsymmetricCipherKeyPair subKP, String _subDN, AsymmetricCipherKeyPair issKP, String _issDN)
    throws IOException, OperatorCreationException
{
    RSAKeyParameters lwPubKey = (RSAKeyParameters)subKP.getPublic();

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(
        new X500Name(_issDN),
        allocateSerialNumber(),
        new Date(System.currentTimeMillis()),
        new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
        new X500Name(_subDN),
        new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPublicKey(lwPubKey.getModulus(), lwPubKey.getExponent()))
    );

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build((AsymmetricKeyParameter)issKP.getPrivate());


    return v1CertGen.build(sigGen);
}
项目:bc-java    文件:CMSTestUtil.java   
public static X509CertificateHolder makeCertificate(AsymmetricCipherKeyPair subKP, String _subDN, AsymmetricCipherKeyPair issKP, String _issDN, boolean _ca)
    throws IOException, OperatorCreationException
{
    RSAKeyParameters lwPubKey = (RSAKeyParameters)subKP.getPublic();

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
        new X500Name(_issDN),
        allocateSerialNumber(),
        new Date(System.currentTimeMillis()),
        new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
        new X500Name(_subDN),
        new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPublicKey(lwPubKey.getModulus(), lwPubKey.getExponent()))
    );

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build((AsymmetricKeyParameter)issKP.getPrivate());

    v3CertGen.addExtension(
        X509Extension.basicConstraints,
        false,
        new BasicConstraints(_ca));

    return v3CertGen.build(sigGen);
}
项目:xitk    文件:P12KeyGenerator.java   
private KeyPairWithSubjectPublicKeyInfo genRSAKeypair(int keysize,
        BigInteger publicExponent, SecureRandom random) throws Exception {
    KeyPair kp = KeyUtil.generateRSAKeypair(keysize, publicExponent, random);
    java.security.interfaces.RSAPublicKey rsaPubKey =
            (java.security.interfaces.RSAPublicKey) kp.getPublic();

    SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
            new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE),
            new RSAPublicKey(rsaPubKey.getModulus(), rsaPubKey.getPublicExponent()));
    return new KeyPairWithSubjectPublicKeyInfo(kp, spki);
}
项目:ReCRED_FIDO_UAF_OIDC    文件:KeyCodec.java   
public static PublicKey getRSAPublicKey(byte[] encodedPubKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    RSAPublicKey pubKey8 = RSAPublicKey.getInstance(encodedPubKey);
    SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(new RSAKeyParameters(false, pubKey8.getModulus(), pubKey8.getPublicExponent()));
    X509EncodedKeySpec spec = new X509EncodedKeySpec(info.getEncoded());
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePublic(spec);
}
项目:kisso    文件:RsaKeyHelper.java   
public static java.security.interfaces.RSAPublicKey createPublicKey(BigInteger n, BigInteger e) {
    try {
        return (java.security.interfaces.RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(n, e));
    } catch (Exception var3) {
        throw new RuntimeException(var3);
    }
}
项目:PasswordSafe    文件:Crypto.java   
public static APublicKey getRSAPublicKey(byte[] b) throws Exception
{
    ASN1InputStream in = new ASN1InputStream(b);
    try
    {
        ASN1Primitive x = in.readObject();
        RSAPublicKey k = RSAPublicKey.getInstance(x);

        return new APublicKey(new RSAKeyParameters(false, k.getModulus(), k.getPublicExponent()));
    }
    finally
    {
        CKit.close(in);
    }
}
项目:UAF    文件:KeyCodec.java   
public static PublicKey getRSAPublicKey(byte[] encodedPubKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    RSAPublicKey pubKey8 = RSAPublicKey.getInstance(encodedPubKey);
    SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(new RSAKeyParameters(false, pubKey8.getModulus(), pubKey8.getPublicExponent()));
    X509EncodedKeySpec spec = new X509EncodedKeySpec(info.getEncoded());
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePublic(spec);
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * makes RSA public key from PEM string.
 *
 * @param s PEM string that contains the key
 * @return
 * @see JCERSAPublicKey
 */
public static RSAPublicKey extractPublicRSAKey(final String s) {
    RSAPublicKey theKey;
    try {
        theKey = new RSAKeyEncoder().parsePEMPublicKey(s);
    } catch (final Exception e) {
        logger.warn("Encryption.extractPublicRSAKey: Caught exception:" + e.getMessage(), e);
        theKey = null;
    }

    return theKey;
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * makes RSA private key from PEM string.
 *
 * @param s PEM string that contains the key
 * @return
 * @see JCERSAPublicKey
 */
public static RSAKeyPair extractRSAKeyPair(final String s) {
    RSAKeyPair rsaKeyPair;
    try {
        // parse
        final PEMParser parser = new PEMParser(new StringReader(s));
        final Object o = parser.readObject();
        parser.close();
        // check types
        if (!(o instanceof PEMKeyPair)) {
            throw new IOException("Encryption.extractRSAKeyPair: no private key found in string '" + s + "'");
        }
        final PEMKeyPair keyPair = (PEMKeyPair) o;
        if (keyPair.getPrivateKeyInfo() == null) {
            throw new IOException("Encryption.extractRSAKeyPair: no private key found in key pair of string '" + s + "'");
        }
        if (keyPair.getPublicKeyInfo() == null) {
            throw new IOException("Encryption.extractRSAKeyPair: no public key found in key pair of string '" + s + "'");
        }

        // convert keys and pack them together into a key pair
        final RSAPrivateCrtKey privateKey = new TempJCERSAPrivateCrtKey(keyPair.getPrivateKeyInfo());
        logger.debug("JCEPrivateKey={}", privateKey);
        final RSAPublicKey publicKey = new TempJCERSAPublicKey(keyPair.getPublicKeyInfo());
        rsaKeyPair = new RSAKeyPair(publicKey, privateKey);

    } catch (final Exception e) {
        logger.warn("Encryption.extractPrivateRSAKey: Caught exception:" + e.getMessage());
        rsaKeyPair = null;
    }

    return rsaKeyPair;
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * Create a key based on the parameters.
 *
 * @param modulus
 * @param publicExponent
 * @return the key
 */
public static RSAPublicKey getRSAPublicKey(final BigInteger modulus, final BigInteger publicExponent) {
    try {
        return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
    } catch (final GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * converts a RSAPublicKey into PKCS1-encoding (ASN.1).
 *
 * @param pubKeyStruct
 * @return PKCS1-encoded RSA PUBLIC KEY
 * @see JCERSAPublicKey
 */
public static byte[] getPKCS1EncodingFromRSAPublicKey(final RSAPublicKey pubKeyStruct) {
    try {
        final RSAPublicKeyStructure myKey = new RSAPublicKeyStructure(pubKeyStruct.getModulus(), pubKeyStruct.getPublicExponent());
        final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        final ASN1OutputStream aOut = new ASN1OutputStream(bOut);
        aOut.writeObject(myKey.toASN1Object());
        aOut.close();
        return bOut.toByteArray();
    } catch (final Exception e) {
        return null;
    }
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * converts a JCERSAPublicKey into PEM/PKCS1-encoding.
 *
 * @param rsaPublicKey
 * @return PEM-encoded RSA PUBLIC KEY
 */
public static String getPEMStringFromRSAPublicKey(final RSAPublicKey rsaPublicKey) {

    // mrk: this was awful to program. Remeber: There are two entirely
    // different
    // standard formats for rsa public keys. Bouncy castle does only support
    // the
    // one we can't use for TOR directories.

    final StringBuffer tmpDirSigningKey = new StringBuffer();

    try {

        tmpDirSigningKey.append("-----BEGIN RSA PUBLIC KEY-----\n");

        final byte[] base64Encoding = Base64.encode(getPKCS1EncodingFromRSAPublicKey(rsaPublicKey));
        for (int i = 0; i < base64Encoding.length; i++) {
            tmpDirSigningKey.append((char) base64Encoding[i]);
            if (((i + 1) % 64) == 0) {
                tmpDirSigningKey.append("\n");
            }
        }
        tmpDirSigningKey.append("\n");

        tmpDirSigningKey.append("-----END RSA PUBLIC KEY-----\n");
    } catch (final Exception e) {
        return null;
    }

    return tmpDirSigningKey.toString();
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * makes RSA public key from PEM string.
 *
 * @param s PEM string that contains the key
 * @return
 * @see JCERSAPublicKey
 */
public static RSAPublicKey extractPublicRSAKey(final String s) {
    RSAPublicKey theKey;
    try {
        theKey = new RSAKeyEncoder().parsePEMPublicKey(s);
    } catch (final Exception e) {
        logger.warn("Encryption.extractPublicRSAKey: Caught exception:" + e.getMessage(), e);
        theKey = null;
    }

    return theKey;
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * makes RSA private key from PEM string.
 *
 * @param s PEM string that contains the key
 * @return
 * @see JCERSAPublicKey
 */
public static RSAKeyPair extractRSAKeyPair(final String s) {
    RSAKeyPair rsaKeyPair;
    try {
        // parse
        final PEMParser parser = new PEMParser(new StringReader(s));
        final Object o = parser.readObject();
        parser.close();
        // check types
        if (!(o instanceof PEMKeyPair)) {
            throw new IOException("Encryption.extractRSAKeyPair: no private key found in string '" + s + "'");
        }
        final PEMKeyPair keyPair = (PEMKeyPair) o;
        if (keyPair.getPrivateKeyInfo() == null) {
            throw new IOException("Encryption.extractRSAKeyPair: no private key found in key pair of string '" + s + "'");
        }
        if (keyPair.getPublicKeyInfo() == null) {
            throw new IOException("Encryption.extractRSAKeyPair: no public key found in key pair of string '" + s + "'");
        }

        // convert keys and pack them together into a key pair
        final RSAPrivateCrtKey privateKey = new TempJCERSAPrivateCrtKey(keyPair.getPrivateKeyInfo());
        logger.debug("JCEPrivateKey={}", privateKey);
        final RSAPublicKey publicKey = new TempJCERSAPublicKey(keyPair.getPublicKeyInfo());
        rsaKeyPair = new RSAKeyPair(publicKey, privateKey);

    } catch (final Exception e) {
        logger.warn("Encryption.extractPrivateRSAKey: Caught exception:" + e.getMessage());
        rsaKeyPair = null;
    }

    return rsaKeyPair;
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * Create a key based on the parameters.
 *
 * @param modulus
 * @param publicExponent
 * @return the key
 */
public static RSAPublicKey getRSAPublicKey(final BigInteger modulus, final BigInteger publicExponent) {
    try {
        return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
    } catch (final GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * converts a RSAPublicKey into PKCS1-encoding (ASN.1).
 *
 * @param pubKeyStruct
 * @return PKCS1-encoded RSA PUBLIC KEY
 * @see JCERSAPublicKey
 */
public static byte[] getPKCS1EncodingFromRSAPublicKey(final RSAPublicKey pubKeyStruct) {
    try {
        final RSAPublicKeyStructure myKey = new RSAPublicKeyStructure(pubKeyStruct.getModulus(), pubKeyStruct.getPublicExponent());
        final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        final ASN1OutputStream aOut = new ASN1OutputStream(bOut);
        aOut.writeObject(myKey.toASN1Object());
        aOut.close();
        return bOut.toByteArray();
    } catch (final Exception e) {
        return null;
    }
}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * converts a JCERSAPublicKey into PEM/PKCS1-encoding.
 *
 * @param rsaPublicKey
 * @return PEM-encoded RSA PUBLIC KEY
 */
public static String getPEMStringFromRSAPublicKey(final RSAPublicKey rsaPublicKey) {

    // mrk: this was awful to program. Remeber: There are two entirely
    // different
    // standard formats for rsa public keys. Bouncy castle does only support
    // the
    // one we can't use for TOR directories.

    final StringBuffer tmpDirSigningKey = new StringBuffer();

    try {

        tmpDirSigningKey.append("-----BEGIN RSA PUBLIC KEY-----\n");

        final byte[] base64Encoding = Base64.encode(getPKCS1EncodingFromRSAPublicKey(rsaPublicKey));
        for (int i = 0; i < base64Encoding.length; i++) {
            tmpDirSigningKey.append((char) base64Encoding[i]);
            if (((i + 1) % 64) == 0) {
                tmpDirSigningKey.append("\n");
            }
        }
        tmpDirSigningKey.append("\n");

        tmpDirSigningKey.append("-----END RSA PUBLIC KEY-----\n");
    } catch (final Exception e) {
        return null;
    }

    return tmpDirSigningKey.toString();
}
项目:PasswordSafe    文件:Crypto.java   
public static RSAPublicKey toRSAPublicKey(RSAPublicKeySpec k)
{
    return new RSAPublicKey(k.getModulus(), k.getPublicExponent());
}
项目:PasswordSafe    文件:Crypto.java   
public static byte[] toByteArray(RSAPublicKeySpec spec) throws Exception
{
    RSAPublicKey k = toRSAPublicKey(spec);
    return k.getEncoded();
}
项目:PasswordSafe    文件:Crypto.java   
public static RSAPublicKey toRSAPublicKey(RSAKeyParameters k) throws Exception
{
    return new RSAPublicKey(k.getModulus(), k.getExponent());
}
项目:irma_future_id    文件:OAEPTest.java   
private void baseOaepTest(
    int     id,
    byte[]  pubKeyEnc,
    byte[]  privKeyEnc,
    byte[]  output)
    throws Exception
{
    ByteArrayInputStream    bIn = new ByteArrayInputStream(pubKeyEnc);
    ASN1InputStream         dIn = new ASN1InputStream(bIn);

    //
    // extract the public key info.
    //
    RSAPublicKey pubStruct;

    pubStruct = RSAPublicKey.getInstance(new SubjectPublicKeyInfo((ASN1Sequence)dIn.readObject()).parsePublicKey());


    bIn = new ByteArrayInputStream(privKeyEnc);
    dIn = new ASN1InputStream(bIn);

    //
    // extract the private key info.
    //
    RSAPrivateKey privStruct;

    privStruct = RSAPrivateKey.getInstance(new PrivateKeyInfo((ASN1Sequence)dIn.readObject()).parsePrivateKey());

    RSAKeyParameters    pubParameters = new RSAKeyParameters(
                                                false,
                                                pubStruct.getModulus(),
                                                pubStruct.getPublicExponent());

    RSAKeyParameters    privParameters = new RSAPrivateCrtKeyParameters(
                                                privStruct.getModulus(),
                                                privStruct.getPublicExponent(),
                                                privStruct.getPrivateExponent(),
                                                privStruct.getPrime1(),
                                                privStruct.getPrime2(),
                                                privStruct.getExponent1(),
                                                privStruct.getExponent2(),
                                                privStruct.getCoefficient());

    byte[]  input = new byte[]
                { (byte)0x54, (byte)0x85, (byte)0x9b, (byte)0x34, (byte)0x2c, (byte)0x49, (byte)0xea, (byte)0x2a };

    encDec("id(" + id + ")", pubParameters, privParameters, seed, input, output);

}
项目:bc-java    文件:OAEPTest.java   
private void baseOaepTest(
    int     id,
    byte[]  pubKeyEnc,
    byte[]  privKeyEnc,
    byte[]  output)
    throws Exception
{
    ByteArrayInputStream    bIn = new ByteArrayInputStream(pubKeyEnc);
    ASN1InputStream         dIn = new ASN1InputStream(bIn);

    //
    // extract the public key info.
    //
    RSAPublicKey pubStruct;

    pubStruct = RSAPublicKey.getInstance(new SubjectPublicKeyInfo((ASN1Sequence)dIn.readObject()).parsePublicKey());


    bIn = new ByteArrayInputStream(privKeyEnc);
    dIn = new ASN1InputStream(bIn);

    //
    // extract the private key info.
    //
    RSAPrivateKey privStruct;

    privStruct = RSAPrivateKey.getInstance(new PrivateKeyInfo((ASN1Sequence)dIn.readObject()).parsePrivateKey());

    RSAKeyParameters    pubParameters = new RSAKeyParameters(
                                                false,
                                                pubStruct.getModulus(),
                                                pubStruct.getPublicExponent());

    RSAKeyParameters    privParameters = new RSAPrivateCrtKeyParameters(
                                                privStruct.getModulus(),
                                                privStruct.getPublicExponent(),
                                                privStruct.getPrivateExponent(),
                                                privStruct.getPrime1(),
                                                privStruct.getPrime2(),
                                                privStruct.getExponent1(),
                                                privStruct.getExponent2(),
                                                privStruct.getCoefficient());

    byte[]  input = new byte[]
                { (byte)0x54, (byte)0x85, (byte)0x9b, (byte)0x34, (byte)0x2c, (byte)0x49, (byte)0xea, (byte)0x2a };

    encDec("id(" + id + ")", pubParameters, privParameters, seed, input, output);

}
项目:silvertunnel-monteux    文件:Encryption.java   
/**
 * encrypt data with asymmetric key. create asymmetrical encrypted data:<br>
 * <ul>
 * <li>OAEP padding [42 bytes] (RSA-encrypted)</li>
 * <li>Symmetric key [16 bytes] FIXME: we assume that we ALWAYS need this</li>
 * <li>First part of data [70 bytes]</li>
 * <li>Second part of data [x-70 bytes] (Symmetrically encrypted)</li>
 * </ul>
 * encrypt and store in result
 *
 * @param pub
 * @param symmetricKey AES key
 * @param data         to be encrypted, needs currently to be at least 70 bytes long
 * @return the first half of the key exchange, ready to be send to the other
 * partner
 */
public static byte[] asymEncrypt(final RSAPublicKey pub, final byte[] symmetricKey, final byte[] data) throws TorException {
    if (data == null) {
        throw new NullPointerException("can't encrypt NULL data");
    }

    HybridEncryption hybridEncryption = new HybridEncryption();

    return hybridEncryption.encrypt(data, pub, symmetricKey);
}