Search in sources :

Example 11 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project jersey by jersey.

the class RsaSha1Method method sign.

/**
     * Generates the RSA-SHA1 signature of OAuth request elements.
     *
     * @param baseString the combined OAuth elements to sign.
     * @param secrets the secrets object containing the private key for generating the signature.
     * @return the OAuth signature, in base64-encoded form.
     * @throws InvalidSecretException if the supplied secret is not valid.
     */
@Override
public String sign(final String baseString, final OAuth1Secrets secrets) throws InvalidSecretException {
    final Signature signature;
    try {
        signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    } catch (final NoSuchAlgorithmException nsae) {
        throw new IllegalStateException(nsae);
    }
    byte[] decodedPrivateKey;
    try {
        decodedPrivateKey = Base64.decode(secrets.getConsumerSecret());
    } catch (final IOException ioe) {
        throw new InvalidSecretException(LocalizationMessages.ERROR_INVALID_CONSUMER_SECRET(ioe));
    }
    final KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance(KEY_TYPE);
    } catch (final NoSuchAlgorithmException nsae) {
        throw new IllegalStateException(nsae);
    }
    final EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedPrivateKey);
    final RSAPrivateKey rsaPrivateKey;
    try {
        rsaPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (final InvalidKeySpecException ikse) {
        throw new IllegalStateException(ikse);
    }
    try {
        signature.initSign(rsaPrivateKey);
    } catch (final InvalidKeyException ike) {
        throw new IllegalStateException(ike);
    }
    try {
        signature.update(baseString.getBytes());
    } catch (final SignatureException se) {
        throw new IllegalStateException(se);
    }
    final byte[] rsasha1;
    try {
        rsasha1 = signature.sign();
    } catch (final SignatureException se) {
        throw new IllegalStateException(se);
    }
    return Base64.encode(rsasha1);
}
Also used : NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) Signature(java.security.Signature) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) KeyFactory(java.security.KeyFactory) EncodedKeySpec(java.security.spec.EncodedKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec)

Example 12 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project netty by netty.

the class SslContext method generateKeySpec.

/**
     * Generates a key specification for an (encrypted) private key.
     *
     * @param password characters, if {@code null} an unencrypted key is assumed
     * @param key bytes of the DER encoded private key
     *
     * @return a key specification
     *
     * @throws IOException if parsing {@code key} fails
     * @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unkown
     * @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unkown
     * @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated
     * @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt
     *                             {@code key}
     * @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty
     */
protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException {
    if (password == null) {
        return new PKCS8EncodedKeySpec(key);
    }
    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
    Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());
    return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 13 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project platformlayer by platformlayer.

the class KeyParser method parse.

public Object parse(String s) {
    Object key = null;
    if (key == null) {
        if (s.contains(BEGIN_PRIVATE_KEY)) {
            String payload = s.substring(s.indexOf(BEGIN_PRIVATE_KEY) + BEGIN_PRIVATE_KEY.length());
            if (payload.contains(END_PRIVATE_KEY)) {
                payload = payload.substring(0, payload.indexOf(END_PRIVATE_KEY));
                key = tryParsePemFormat(payload);
            }
        }
    }
    if (key == null) {
        try {
            PemReader reader = new PemReader(new StringReader(s));
            PemObject pemObject = reader.readPemObject();
            reader.close();
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pemObject.getContent());
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = kf.generatePrivate(keySpec);
            if (privateKey instanceof RSAPrivateCrtKey) {
                RSAPrivateCrtKey rsaPrivateCrtKey = (RSAPrivateCrtKey) privateKey;
                RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(rsaPrivateCrtKey.getModulus(), rsaPrivateCrtKey.getPublicExponent());
                PublicKey publicKey = kf.generatePublic(publicKeySpec);
                key = new KeyPair(publicKey, privateKey);
            } else {
                key = privateKey;
            }
        } catch (Exception e) {
            log.debug("Error reading pem data", e);
            return null;
        }
    }
    if (key == null) {
        try {
            // TODO: Check if looks like base64??
            byte[] fromBase64 = Base64.decode(s);
            key = parse(fromBase64);
        } catch (Exception e) {
            log.debug("Cannot decode as base64", e);
        }
    }
    return key;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) PublicKey(java.security.PublicKey) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) StringReader(java.io.StringReader) PemObject(org.bouncycastle.util.io.pem.PemObject) KeyFactory(java.security.KeyFactory)

Example 14 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project dex2jar by pxb1988.

the class ApkSign method doCommandLine.

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();
        return;
    }
    Path apkIn = new File(remainingArgs[0]).toPath();
    if (!Files.exists(apkIn)) {
        System.err.println(apkIn + " is not exists");
        usage();
        return;
    }
    if (output == null) {
        if (Files.isDirectory(apkIn)) {
            output = new File(apkIn.getFileName() + "-signed.apk").toPath();
        } else {
            output = new File(getBaseName(apkIn.getFileName().toString()) + "-signed.apk").toPath();
        }
    }
    if (Files.exists(output) && !forceOverwrite) {
        System.err.println(output + " exists, use --force to overwrite");
        usage();
        return;
    }
    Path tmp = null;
    try {
        final Path realJar;
        if (Files.isDirectory(apkIn)) {
            realJar = Files.createTempFile("d2j", ".jar");
            tmp = realJar;
            System.out.println("zipping " + apkIn + " -> " + realJar);
            try (FileSystem fs = createZip(realJar)) {
                final Path outRoot = fs.getPath("/");
                walkJarOrDir(apkIn, new FileVisitorX() {

                    @Override
                    public void visitFile(Path file, String relative) throws IOException {
                        Path target = outRoot.resolve(relative);
                        createParentDirectories(target);
                        Files.copy(file, target);
                    }
                });
            }
        } else {
            realJar = apkIn;
        }
        AbstractJarSign signer;
        if (tiny) {
            signer = new TinySignImpl();
        } else {
            try {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(ApkSign.class.getResourceAsStream("ApkSign.cer"));
                KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA");
                PrivateKey privateKey = rSAKeyFactory.generatePrivate(new PKCS8EncodedKeySpec(ZipUtil.toByteArray(ApkSign.class.getResourceAsStream("ApkSign.private"))));
                signer = new SunJarSignImpl(cert, privateKey);
            } catch (Exception cnfe) {
                signer = new TinySignImpl();
            }
        }
        signer.sign(apkIn.toFile(), output.toFile());
        System.out.println("sign " + realJar + " -> " + output);
    } finally {
        if (tmp != null) {
            Files.deleteIfExists(tmp);
        }
    }
}
Also used : Path(java.nio.file.Path) SunJarSignImpl(com.googlecode.d2j.signapk.SunJarSignImpl) PrivateKey(java.security.PrivateKey) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) AbstractJarSign(com.googlecode.d2j.signapk.AbstractJarSign) FileSystem(java.nio.file.FileSystem) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) File(java.io.File) KeyFactory(java.security.KeyFactory) TinySignImpl(com.googlecode.d2j.signapk.TinySignImpl)

Example 15 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project xabber-android by redsolution.

the class AccountTable method getKeyPair.

static KeyPair getKeyPair(Cursor cursor) {
    byte[] publicKeyBytes = cursor.getBlob(cursor.getColumnIndex(Fields.PUBLIC_KEY));
    byte[] privateKeyBytes = cursor.getBlob(cursor.getColumnIndex(Fields.PRIVATE_KEY));
    if (privateKeyBytes == null || publicKeyBytes == null) {
        return null;
    }
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    PublicKey publicKey;
    PrivateKey privateKey;
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("DSA");
        publicKey = keyFactory.generatePublic(publicKeySpec);
        privateKey = keyFactory.generatePrivate(privateKeySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new RuntimeException(e);
    }
    return new KeyPair(publicKey, privateKey);
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory)

Aggregations

PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)218 KeyFactory (java.security.KeyFactory)172 PrivateKey (java.security.PrivateKey)144 CertificateFactory (java.security.cert.CertificateFactory)86 ByteArrayInputStream (java.io.ByteArrayInputStream)85 Certificate (java.security.cert.Certificate)72 X509Certificate (java.security.cert.X509Certificate)71 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)59 Entry (java.security.KeyStore.Entry)53 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)53 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)45 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)42 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)37 PublicKey (java.security.PublicKey)36 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)29 IOException (java.io.IOException)28 SecretKey (javax.crypto.SecretKey)27 InvalidKeyException (java.security.InvalidKeyException)25 Key (java.security.Key)24 KeyStoreException (java.security.KeyStoreException)15