Search in sources :

Example 1 with PEMException

use of com.github.zhenwei.pkix.openssl.PEMException in project LinLong-Java by zhenwei1108.

the class PEMUtilities method getKey.

private static SecretKey getKey(JcaJceHelper helper, char[] password, String algorithm, int keyLength, byte[] salt, boolean des2) throws PEMException {
    try {
        PBEKeySpec spec = new PBEKeySpec(password, salt, 1, keyLength * 8);
        SecretKeyFactory keyFactory = helper.createSecretKeyFactory("PBKDF-OpenSSL");
        byte[] key = keyFactory.generateSecret(spec).getEncoded();
        if (des2 && key.length >= 24) {
            // For DES2, we must copy first 8 bytes into the last 8 bytes.
            System.arraycopy(key, 0, key, 16, 8);
        }
        return new SecretKeySpec(key, algorithm);
    } catch (GeneralSecurityException e) {
        throw new PEMException("Unable to create OpenSSL PBDKF: " + e.getMessage(), e);
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKeySpec(javax.crypto.spec.SecretKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) PEMException(com.github.zhenwei.pkix.openssl.PEMException) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 2 with PEMException

use of com.github.zhenwei.pkix.openssl.PEMException in project LinLong-Java by zhenwei1108.

the class PEMUtilities method crypt.

static byte[] crypt(boolean encrypt, JcaJceHelper helper, byte[] bytes, char[] password, String dekAlgName, byte[] iv) throws PEMException {
    AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
    String alg;
    String blockMode = "CBC";
    String padding = "PKCS5Padding";
    Key sKey;
    // Figure out block mode and padding.
    if (dekAlgName.endsWith("-CFB")) {
        blockMode = "CFB";
        padding = "NoPadding";
    }
    if (dekAlgName.endsWith("-ECB") || "DES-EDE".equals(dekAlgName) || "DES-EDE3".equals(dekAlgName)) {
        // ECB is actually the default (though seldom used) when OpenSSL
        // uses DES-EDE (des2) or DES-EDE3 (des3).
        blockMode = "ECB";
        paramSpec = null;
    }
    if (dekAlgName.endsWith("-OFB")) {
        blockMode = "OFB";
        padding = "NoPadding";
    }
    // Figure out algorithm and key size.
    if (dekAlgName.startsWith("DES-EDE")) {
        alg = "DESede";
        // "DES-EDE" is actually des2 in OpenSSL-speak!
        // "DES-EDE3" is des3.
        boolean des2 = !dekAlgName.startsWith("DES-EDE3");
        sKey = getKey(helper, password, alg, 24, iv, des2);
    } else if (dekAlgName.startsWith("DES-")) {
        alg = "DES";
        sKey = getKey(helper, password, alg, 8, iv);
    } else if (dekAlgName.startsWith("BF-")) {
        alg = "Blowfish";
        sKey = getKey(helper, password, alg, 16, iv);
    } else if (dekAlgName.startsWith("RC2-")) {
        alg = "RC2";
        int keyBits = 128;
        if (dekAlgName.startsWith("RC2-40-")) {
            keyBits = 40;
        } else if (dekAlgName.startsWith("RC2-64-")) {
            keyBits = 64;
        }
        sKey = getKey(helper, password, alg, keyBits / 8, iv);
        if (// ECB block mode
        paramSpec == null) {
            paramSpec = new RC2ParameterSpec(keyBits);
        } else {
            paramSpec = new RC2ParameterSpec(keyBits, iv);
        }
    } else if (dekAlgName.startsWith("AES-")) {
        alg = "AES";
        byte[] salt = iv;
        if (salt.length > 8) {
            salt = new byte[8];
            System.arraycopy(iv, 0, salt, 0, 8);
        }
        int keyBits;
        if (dekAlgName.startsWith("AES-128-")) {
            keyBits = 128;
        } else if (dekAlgName.startsWith("AES-192-")) {
            keyBits = 192;
        } else if (dekAlgName.startsWith("AES-256-")) {
            keyBits = 256;
        } else {
            throw new EncryptionException("unknown AES encryption with private key");
        }
        sKey = getKey(helper, password, "AES", keyBits / 8, salt);
    } else {
        throw new EncryptionException("unknown encryption with private key");
    }
    String transformation = alg + "/" + blockMode + "/" + padding;
    try {
        Cipher c = helper.createCipher(transformation);
        int mode = encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE;
        if (// ECB block mode
        paramSpec == null) {
            c.init(mode, sKey);
        } else {
            c.init(mode, sKey, paramSpec);
        }
        return c.doFinal(bytes);
    } catch (Exception e) {
        throw new EncryptionException("exception using cipher - please check password and data.", e);
    }
}
Also used : EncryptionException(com.github.zhenwei.pkix.openssl.EncryptionException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) RC2ParameterSpec(javax.crypto.spec.RC2ParameterSpec) Cipher(javax.crypto.Cipher) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) Key(java.security.Key) SecretKey(javax.crypto.SecretKey) EncryptionException(com.github.zhenwei.pkix.openssl.EncryptionException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) GeneralSecurityException(java.security.GeneralSecurityException) PEMException(com.github.zhenwei.pkix.openssl.PEMException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 3 with PEMException

use of com.github.zhenwei.pkix.openssl.PEMException in project LinLong-Java by zhenwei1108.

the class PEMUtilities method crypt.

static byte[] crypt(boolean encrypt, byte[] bytes, char[] password, String dekAlgName, byte[] iv) throws PEMException {
    byte[] ivValue = iv;
    String blockMode = "CBC";
    BlockCipher engine;
    BlockCipherPadding padding = new PKCS7Padding();
    KeyParameter sKey;
    // Figure out block mode and padding.
    if (dekAlgName.endsWith("-CFB")) {
        blockMode = "CFB";
        padding = null;
    }
    if (dekAlgName.endsWith("-ECB") || "DES-EDE".equals(dekAlgName) || "DES-EDE3".equals(dekAlgName)) {
        // ECB is actually the default (though seldom used) when OpenSSL
        // uses DES-EDE (des2) or DES-EDE3 (des3).
        blockMode = "ECB";
        ivValue = null;
    }
    if (dekAlgName.endsWith("-OFB")) {
        blockMode = "OFB";
        padding = null;
    }
    // Figure out algorithm and key size.
    if (dekAlgName.startsWith("DES-EDE")) {
        // "DES-EDE" is actually des2 in OpenSSL-speak!
        // "DES-EDE3" is des3.
        boolean des2 = !dekAlgName.startsWith("DES-EDE3");
        sKey = getKey(password, 24, iv, des2);
        engine = new DESedeEngine();
    } else if (dekAlgName.startsWith("DES-")) {
        sKey = getKey(password, 8, iv);
        engine = new DESEngine();
    } else if (dekAlgName.startsWith("BF-")) {
        sKey = getKey(password, 16, iv);
        engine = new BlowfishEngine();
    } else if (dekAlgName.startsWith("RC2-")) {
        int keyBits = 128;
        if (dekAlgName.startsWith("RC2-40-")) {
            keyBits = 40;
        } else if (dekAlgName.startsWith("RC2-64-")) {
            keyBits = 64;
        }
        sKey = new RC2Parameters(getKey(password, keyBits / 8, iv).getKey(), keyBits);
        ;
        engine = new RC2Engine();
    } else if (dekAlgName.startsWith("AES-")) {
        byte[] salt = iv;
        if (salt.length > 8) {
            salt = new byte[8];
            System.arraycopy(iv, 0, salt, 0, 8);
        }
        int keyBits;
        if (dekAlgName.startsWith("AES-128-")) {
            keyBits = 128;
        } else if (dekAlgName.startsWith("AES-192-")) {
            keyBits = 192;
        } else if (dekAlgName.startsWith("AES-256-")) {
            keyBits = 256;
        } else {
            throw new EncryptionException("unknown AES encryption with private key: " + dekAlgName);
        }
        sKey = getKey(password, keyBits / 8, salt);
        engine = new AESEngine();
    } else {
        throw new EncryptionException("unknown encryption with private key: " + dekAlgName);
    }
    if (blockMode.equals("CBC")) {
        engine = new CBCBlockCipher(engine);
    } else if (blockMode.equals("CFB")) {
        engine = new CFBBlockCipher(engine, engine.getBlockSize() * 8);
    } else if (blockMode.equals("OFB")) {
        engine = new OFBBlockCipher(engine, engine.getBlockSize() * 8);
    }
    try {
        BufferedBlockCipher c;
        if (padding == null) {
            c = new BufferedBlockCipher(engine);
        } else {
            c = new PaddedBufferedBlockCipher(engine, padding);
        }
        if (// ECB block mode
        ivValue == null) {
            c.init(encrypt, sKey);
        } else {
            c.init(encrypt, new ParametersWithIV(sKey, ivValue));
        }
        byte[] out = new byte[c.getOutputSize(bytes.length)];
        int procLen = c.processBytes(bytes, 0, bytes.length, out, 0);
        procLen += c.doFinal(out, procLen);
        if (procLen == out.length) {
            return out;
        } else {
            byte[] rv = new byte[procLen];
            System.arraycopy(out, 0, rv, 0, procLen);
            return rv;
        }
    } catch (Exception e) {
        throw new EncryptionException("exception using cipher - please check password and data.", e);
    }
}
Also used : RC2Parameters(com.github.zhenwei.core.crypto.params.RC2Parameters) AESEngine(com.github.zhenwei.core.crypto.engines.AESEngine) OFBBlockCipher(com.github.zhenwei.core.crypto.modes.OFBBlockCipher) PaddedBufferedBlockCipher(com.github.zhenwei.core.crypto.paddings.PaddedBufferedBlockCipher) CBCBlockCipher(com.github.zhenwei.core.crypto.modes.CBCBlockCipher) CFBBlockCipher(com.github.zhenwei.core.crypto.modes.CFBBlockCipher) BufferedBlockCipher(com.github.zhenwei.core.crypto.BufferedBlockCipher) BlockCipher(com.github.zhenwei.core.crypto.BlockCipher) PaddedBufferedBlockCipher(com.github.zhenwei.core.crypto.paddings.PaddedBufferedBlockCipher) OFBBlockCipher(com.github.zhenwei.core.crypto.modes.OFBBlockCipher) KeyParameter(com.github.zhenwei.core.crypto.params.KeyParameter) BlowfishEngine(com.github.zhenwei.core.crypto.engines.BlowfishEngine) RC2Engine(com.github.zhenwei.core.crypto.engines.RC2Engine) EncryptionException(com.github.zhenwei.pkix.openssl.EncryptionException) PEMException(com.github.zhenwei.pkix.openssl.PEMException) ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) PKCS7Padding(com.github.zhenwei.core.crypto.paddings.PKCS7Padding) CFBBlockCipher(com.github.zhenwei.core.crypto.modes.CFBBlockCipher) DESEngine(com.github.zhenwei.core.crypto.engines.DESEngine) BlockCipherPadding(com.github.zhenwei.core.crypto.paddings.BlockCipherPadding) BufferedBlockCipher(com.github.zhenwei.core.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(com.github.zhenwei.core.crypto.paddings.PaddedBufferedBlockCipher) EncryptionException(com.github.zhenwei.pkix.openssl.EncryptionException) CBCBlockCipher(com.github.zhenwei.core.crypto.modes.CBCBlockCipher) DESedeEngine(com.github.zhenwei.core.crypto.engines.DESedeEngine)

Example 4 with PEMException

use of com.github.zhenwei.pkix.openssl.PEMException in project LinLong-Java by zhenwei1108.

the class JceOpenSSLPKCS8DecryptorProviderBuilder method build.

public InputDecryptorProvider build(final char[] password) throws OperatorCreationException {
    return new InputDecryptorProvider() {

        public InputDecryptor get(final AlgorithmIdentifier algorithm) throws OperatorCreationException {
            final Cipher cipher;
            try {
                if (PEMUtilities.isPKCS5Scheme2(algorithm.getAlgorithm())) {
                    PBES2Parameters params = PBES2Parameters.getInstance(algorithm.getParameters());
                    KeyDerivationFunc func = params.getKeyDerivationFunc();
                    EncryptionScheme scheme = params.getEncryptionScheme();
                    PBKDF2Params defParams = (PBKDF2Params) func.getParameters();
                    int iterationCount = defParams.getIterationCount().intValue();
                    byte[] salt = defParams.getSalt();
                    String oid = scheme.getAlgorithm().getId();
                    SecretKey key;
                    if (PEMUtilities.isHmacSHA1(defParams.getPrf())) {
                        key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(helper, oid, password, salt, iterationCount);
                    } else {
                        key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(helper, oid, password, salt, iterationCount, defParams.getPrf());
                    }
                    cipher = helper.createCipher(oid);
                    AlgorithmParameters algParams = helper.createAlgorithmParameters(oid);
                    algParams.init(scheme.getParameters().toASN1Primitive().getEncoded());
                    cipher.init(Cipher.DECRYPT_MODE, key, algParams);
                } else if (PEMUtilities.isPKCS12(algorithm.getAlgorithm())) {
                    PKCS12PBEParams params = PKCS12PBEParams.getInstance(algorithm.getParameters());
                    cipher = helper.createCipher(algorithm.getAlgorithm().getId());
                    cipher.init(Cipher.DECRYPT_MODE, new PKCS12KeyWithParameters(password, params.getIV(), params.getIterations().intValue()));
                } else if (PEMUtilities.isPKCS5Scheme1(algorithm.getAlgorithm())) {
                    PBEParameter params = PBEParameter.getInstance(algorithm.getParameters());
                    cipher = helper.createCipher(algorithm.getAlgorithm().getId());
                    cipher.init(Cipher.DECRYPT_MODE, new PBKDF1KeyWithParameters(password, new CharToByteConverter() {

                        public String getType() {
                            return "ASCII";
                        }

                        public byte[] convert(char[] password) {
                            // just drop hi-order byte.
                            return Strings.toByteArray(password);
                        }
                    }, params.getSalt(), params.getIterationCount().intValue()));
                } else {
                    throw new PEMException("Unknown algorithm: " + algorithm.getAlgorithm());
                }
                return new InputDecryptor() {

                    public AlgorithmIdentifier getAlgorithmIdentifier() {
                        return algorithm;
                    }

                    public InputStream getInputStream(InputStream encIn) {
                        return new CipherInputStream(encIn, cipher);
                    }
                };
            } catch (IOException e) {
                throw new OperatorCreationException(algorithm.getAlgorithm() + " not available: " + e.getMessage(), e);
            } catch (GeneralSecurityException e) {
                throw new OperatorCreationException(algorithm.getAlgorithm() + " not available: " + e.getMessage(), e);
            }
        }
    };
}
Also used : PBEParameter(com.github.zhenwei.core.asn1.pkcs.PBEParameter) PBES2Parameters(com.github.zhenwei.core.asn1.pkcs.PBES2Parameters) EncryptionScheme(com.github.zhenwei.core.asn1.pkcs.EncryptionScheme) CipherInputStream(com.github.zhenwei.provider.jcajce.io.CipherInputStream) InputDecryptor(com.github.zhenwei.pkix.operator.InputDecryptor) CipherInputStream(com.github.zhenwei.provider.jcajce.io.CipherInputStream) InputStream(java.io.InputStream) PBKDF1KeyWithParameters(com.github.zhenwei.provider.jcajce.PBKDF1KeyWithParameters) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CharToByteConverter(com.github.zhenwei.core.crypto.CharToByteConverter) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) SecretKey(javax.crypto.SecretKey) InputDecryptorProvider(com.github.zhenwei.pkix.operator.InputDecryptorProvider) PKCS12PBEParams(com.github.zhenwei.core.asn1.pkcs.PKCS12PBEParams) PEMException(com.github.zhenwei.pkix.openssl.PEMException) KeyDerivationFunc(com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc) PBKDF2Params(com.github.zhenwei.core.asn1.pkcs.PBKDF2Params) Cipher(javax.crypto.Cipher) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) PKCS12KeyWithParameters(com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters) AlgorithmParameters(java.security.AlgorithmParameters)

Aggregations

PEMException (com.github.zhenwei.pkix.openssl.PEMException)4 GeneralSecurityException (java.security.GeneralSecurityException)3 EncryptionException (com.github.zhenwei.pkix.openssl.EncryptionException)2 Cipher (javax.crypto.Cipher)2 SecretKey (javax.crypto.SecretKey)2 EncryptionScheme (com.github.zhenwei.core.asn1.pkcs.EncryptionScheme)1 KeyDerivationFunc (com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc)1 PBEParameter (com.github.zhenwei.core.asn1.pkcs.PBEParameter)1 PBES2Parameters (com.github.zhenwei.core.asn1.pkcs.PBES2Parameters)1 PBKDF2Params (com.github.zhenwei.core.asn1.pkcs.PBKDF2Params)1 PKCS12PBEParams (com.github.zhenwei.core.asn1.pkcs.PKCS12PBEParams)1 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)1 BlockCipher (com.github.zhenwei.core.crypto.BlockCipher)1 BufferedBlockCipher (com.github.zhenwei.core.crypto.BufferedBlockCipher)1 CharToByteConverter (com.github.zhenwei.core.crypto.CharToByteConverter)1 AESEngine (com.github.zhenwei.core.crypto.engines.AESEngine)1 BlowfishEngine (com.github.zhenwei.core.crypto.engines.BlowfishEngine)1 DESEngine (com.github.zhenwei.core.crypto.engines.DESEngine)1 DESedeEngine (com.github.zhenwei.core.crypto.engines.DESedeEngine)1 RC2Engine (com.github.zhenwei.core.crypto.engines.RC2Engine)1