Jasypt的StandardPBEByteEncryptor使用源码解析

 更新时间:2023年09月01日 10:39:40   作者:codecraft  
这篇文章主要介绍了Jasypt的StandardPBEByteEncryptor使用源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

Jasypt

Jasypt即Java Simplified Encryption,它主要是简化项目加解密的工作,内置提供了很多组件的集成,比如hibernate、spring、spring-security等

示例1

StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
String encryptedPassword = passwordEncryptor.encryptPassword(userPassword);
...
if (passwordEncryptor.checkPassword(inputPassword, encryptedPassword)) {
  // correct!
} else {
  // bad login!
}

示例2

AES256TextEncryptor textEncryptor = new AES256TextEncryptor();
textEncryptor.setPassword(myEncryptionPassword);
String myEncryptedText = textEncryptor.encrypt(myText);
...
String plainText = textEncryptor.decrypt(myEncryptedText);

StandardPBEByteEncryptor

org/jasypt/encryption/pbe/StandardPBEByteEncryptor.java

public final class StandardPBEByteEncryptor implements PBEByteCleanablePasswordEncryptor {
    /**
     * The default algorithm to be used if none specified: PBEWithMD5AndDES.
     */
    public static final String DEFAULT_ALGORITHM = "PBEWithMD5AndDES";
    /**
     * The default number of hashing iterations applied for obtaining the encryption key from the specified password,
     * set to 1000.
     */
    public static final int DEFAULT_KEY_OBTENTION_ITERATIONS = 1000;
    /**
     * The default salt size, only used if the chosen encryption algorithm is not a block algorithm and thus block size
     * cannot be used as salt size.
     */
    public static final int DEFAULT_SALT_SIZE_BYTES = 8;
    /**
     * The default IV size
     */
    public static final int IV_SIZE_IN_BITS = 128;
    // Algorithm (and provider-related info) for Password Based Encoding.
    private String algorithm = DEFAULT_ALGORITHM;
    private String providerName = null;
    private Provider provider = null;
    // Password to be applied. This will NOT have a default value. If none
    // is set during configuration, an exception will be thrown.
    private char[] password = null;
    // Number of hashing iterations to be applied for obtaining the encryption
    // key from the specified password.
    private int keyObtentionIterations = DEFAULT_KEY_OBTENTION_ITERATIONS;
    // SaltGenerator to be used. Initialization of a salt generator is costly,
    // and so default value will be applied only in initialize(), if it finally
    // becomes necessary.
    private SaltGenerator saltGenerator = null;
    // IVGenerator to initialise IV
    private IVGenerator ivGenerator = null;
    // Size in bytes of the IV to be used
    private final int IVSizeBytes = IV_SIZE_IN_BITS;
    // Size in bytes of the salt to be used for obtaining the
    // encryption key. This size will depend on the PBE algorithm being used,
    // and it will be set to the size of the block for the specific
    // chosen algorithm (if the algorithm is not a block algorithm, the
    // default value will be used).
    private int saltSizeBytes = DEFAULT_SALT_SIZE_BYTES;
    //......
}
StandardPBEByteEncryptor实现了PBEByteCleanablePasswordEncryptor接口,而该则集成了PBEByteEncryptor和CleanablePasswordBased接口,PBEByteEncryptor继承了ByteEncryptor、PasswordBased

ByteEncryptor

org/jasypt/encryption/ByteEncryptor.java

public interface ByteEncryptor {
    
    
    /**
     * Encrypt the input message
     * 
     * @param message the message to be encrypted
     * @return the result of encryption
     */
    public byte[] encrypt(byte[] message);

    /**
     * Decrypt an encrypted message
     * 
     * @param encryptedMessage the encrypted message to be decrypted
     * @return the result of decryption
     */
    public byte[] decrypt(byte[] encryptedMessage);
    
}
ByteEncryptor定义了encrypt和decrypt方法

StandardPBEByteEncryptor.encrypt

public byte[] encrypt(final byte[] message) throws EncryptionOperationNotPossibleException {
        if (message == null) {
            return null;
        }
        // Check initialization
        if (!isInitialized()) {
            initialize();
        }
        try {
            final byte[] salt;
            byte[] iv = null;
            final byte[] encryptedMessage;
            if (usingFixedSalt) {
                salt = fixedSaltInUse;
                synchronized (encryptCipher) {
                    encryptedMessage = encryptCipher.doFinal(message);
                }
            }
            else {
                // Create salt
                salt = saltGenerator.generateSalt(saltSizeBytes);
                // Create the IV
                iv = ivGenerator.generateIV(IVSizeBytes);
                IvParameterSpec ivParameterSpec = null;
                if (iv != null) {
                    ivParameterSpec = new IvParameterSpec(iv);
                }
                /*
                 * Perform encryption using the Cipher
                 */
                final PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, keyObtentionIterations,
                            ivParameterSpec);
                synchronized (encryptCipher) {
                    encryptCipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
                    encryptedMessage = encryptCipher.doFinal(message);
                }
            }
            byte[] encryptedMessageWithIV = encryptedMessage;
            if (ivGenerator.includePlainIVInEncryptionResults()) {
                encryptedMessageWithIV = CommonUtils.appendArrays(iv, encryptedMessage);
            }
            // Finally we build an array containing both the unencrypted salt
            // and the result of the encryption. This is done only
            // if the salt generator we are using specifies to do so.
            if (saltGenerator.includePlainSaltInEncryptionResults()) {
                // Insert unhashed salt before the encryption result
                final byte[] encryptedMessageWithIVAndSalt = CommonUtils.appendArrays(salt, encryptedMessageWithIV);
                return encryptedMessageWithIVAndSalt;
            }
            return encryptedMessageWithIV;
        }
        catch (final InvalidKeyException e) {
            // The problem could be not having the unlimited strength policies
            // installed, so better give a usefull error message.
            handleInvalidKeyException(e);
            throw new EncryptionOperationNotPossibleException();
        }
        catch (final Exception e) {
            // If encryption fails, it is more secure not to return any
            // information about the cause in nested exceptions. Simply fail.
            throw new EncryptionOperationNotPossibleException();
        }
    }

 StandardPBEByteEncryptor的encrypt方法,该方法首先判断salt值是固定的和动态的,固定的则是初始化的时候就设置好的,直接从实例属性取,然后直接调用cipher加密

而动态的话,则通过saltGenerator和generateIV来生成salt和iv,之后根据salt、iv和keyObtentionIterations来创建PBEParameterSpec,然后初始化cipher再进行加密

最后通过ivGenerator判断是否需要把iv包含到加密结果中,是则append到前面进去,再通过saltGenerator判断是否应该把slat包含到加密结果中,是则append到前面进去,最后返回解密结果

StandardPBEByteEncryptor.decrypt

public byte[] decrypt(final byte[] encryptedMessage) throws EncryptionOperationNotPossibleException {
        if (encryptedMessage == null) {
            return null;
        }
        // Check initialization
        if (!isInitialized()) {
            initialize();
        }
        if (saltGenerator.includePlainSaltInEncryptionResults()) {
            // Check that the received message is bigger than the salt
            if (encryptedMessage.length <= saltSizeBytes) {
                throw new EncryptionOperationNotPossibleException();
            }
        }
        // if (this.ivGenerator.includePlainIVInEncryptionResults()) {
        // // Check that the received message is bigger than the IV
        // if (encryptedMessage.length <= this.IVSizeBytes) {
        // throw new EncryptionOperationNotPossibleException();
        // }
        // }
        try {
            // If we are using a salt generator which specifies the salt
            // to be included into the encrypted message itself, get it from
            // there. If not, the salt is supposed to be fixed and thus the
            // salt generator can be safely asked for it again.
            byte[] salt = null;
            byte[] encryptedMessageKernel = null;
            if (saltGenerator.includePlainSaltInEncryptionResults()) {
                final int saltStart = 0;
                final int saltSize = saltSizeBytes < encryptedMessage.length ? saltSizeBytes : encryptedMessage.length;
                final int encMesKernelStart = saltSizeBytes < encryptedMessage.length ? saltSizeBytes
                            : encryptedMessage.length;
                final int encMesKernelSize = saltSizeBytes < encryptedMessage.length
                            ? encryptedMessage.length - saltSizeBytes
                            : 0;
                salt = new byte[saltSize];
                encryptedMessageKernel = new byte[encMesKernelSize];
                System.arraycopy(encryptedMessage, saltStart, salt, 0, saltSize);
                System.arraycopy(encryptedMessage, encMesKernelStart, encryptedMessageKernel, 0, encMesKernelSize);
            }
            else if (!usingFixedSalt) {
                salt = saltGenerator.generateSalt(saltSizeBytes);
                encryptedMessageKernel = encryptedMessage;
            }
            else {
                // this.usingFixedSalt == true
                salt = fixedSaltInUse;
                encryptedMessageKernel = encryptedMessage;
            }
            // Logic for IV
            byte[] finalEncryptedMessage;
            byte[] iv;
            if (ivGenerator.includePlainIVInEncryptionResults()) {
                // Extracting the IV
                iv = Arrays.copyOfRange(encryptedMessageKernel, 0, IVSizeBytes / 8);
                finalEncryptedMessage = Arrays.copyOfRange(encryptedMessageKernel, iv.length,
                            encryptedMessageKernel.length);
            }
            else {
                // Fixed IV
                finalEncryptedMessage = encryptedMessageKernel;
                iv = ivGenerator.generateIV(IVSizeBytes);
            }
            final byte[] decryptedMessage;
            if (usingFixedSalt) {
                /*
                 * Fixed salt is being used, therefore no initialization supposedly needed
                 */
                synchronized (decryptCipher) {
                    decryptedMessage = decryptCipher.doFinal(encryptedMessageKernel);
                }
            }
            else {
                /*
                 * Perform decryption using the Cipher
                 */
                IvParameterSpec ivParameterSpec = null;
                if (iv != null) {
                    ivParameterSpec = new IvParameterSpec(iv);
                }
                final PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, keyObtentionIterations,
                            ivParameterSpec);
                synchronized (decryptCipher) {
                    decryptCipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
                    decryptedMessage = decryptCipher.doFinal(finalEncryptedMessage);
                }
            }
            // Return the results
            return decryptedMessage;
        }
        catch (final InvalidKeyException e) {
            // The problem could be not having the unlimited strength policies
            // installed, so better give a usefull error message.
            handleInvalidKeyException(e);
            throw new EncryptionOperationNotPossibleException();
        }
        catch (final Exception e) {
            // If decryption fails, it is more secure not to return any
            // information about the cause in nested exceptions. Simply fail.
            throw new EncryptionOperationNotPossibleException();
        }
    }
StandardPBEByteEncryptor的decrypt方法先通过saltGenerator判断salt是否包含在密文中,是则根据配置的salt的长度从密文取出来salt,之后通过ivGenerator判断iv是否包含在密文中,是则从剩下的密文取出来iv,得到slat和iv之后,对剩下的密文进行解密

小结

StandardPBEByteEncryptor实现了ByteEncryptor的encrypt和decrypt方法,其主要思路就是判断slat、iv是否包含在密文,然后做对应的处理。

doc Jasypt

以上就是Jasypt的StandardPBEByteEncryptor使用源码解析的详细内容,更多关于Jasypt StandardPBEByteEncryptor的资料请关注脚本之家其它相关文章!

相关文章

  • MyBatis saveBatch 性能调优的实现

    MyBatis saveBatch 性能调优的实现

    本文主要介绍了MyBatis saveBatch 性能调优的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • 亲手教你IDEA2020.3创建Javaweb项目的步骤详解

    亲手教你IDEA2020.3创建Javaweb项目的步骤详解

    这篇文章主要介绍了IDEA2020.3创建Javaweb项目的步骤详解,本文是小编手把手教你,通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2021-03-03
  • Gson如何序列化内部类

    Gson如何序列化内部类

    本文介绍如何使用Gson对成员内部类及静态内部类进行序列化/反序列化,帮助大家更好的理解和使用gson库,感兴趣的朋友可以了解下
    2020-11-11
  • spring mvc @PathVariable绑定URI模板变量值方式

    spring mvc @PathVariable绑定URI模板变量值方式

    这篇文章主要介绍了spring mvc @PathVariable绑定URI模板变量值方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • Mybatis批量插入的三种实现方法

    Mybatis批量插入的三种实现方法

    在日常开发中,如果要操作数据库的话,或多或少都会遇到批量数据的处理,本文主要介绍了Mybatis批量插入的三种实现方法,感兴趣的可以了解一下
    2023-10-10
  • java解析xml之jdom解析xml示例分享

    java解析xml之jdom解析xml示例分享

    JDOM是专门为Java打造的API,JDOM采用了Java中的Collection架构来封装集合,是Java爱好者更加熟悉的模式,下面看使用示例
    2014-01-01
  • JAVA实现对阿里云DNS的解析管理

    JAVA实现对阿里云DNS的解析管理

    本文主要介绍了JAVA实现对阿里云DNS的解析管理,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • 手把手教你如何用JAVA连接MYSQL(mysql-connector-j-8.0.32.jar)

    手把手教你如何用JAVA连接MYSQL(mysql-connector-j-8.0.32.jar)

    这篇文章主要介绍了关于如何用JAVA连接MYSQL(mysql-connector-j-8.0.32.jar)的相关资料,文中通过图文介绍的非常详细,对大家学习或者使用MySQL具有一定的参考借鉴价值,需要的朋友可以参考下
    2024-01-01
  • SpringBoot随机数设置及参数间引用的操作步骤

    SpringBoot随机数设置及参数间引用的操作步骤

    在Spring Boot配置文件中设置属性时,除了可以像前面示例中显示的配置属性值外,还可以使用随机值和参数间引用对属性值进行设置。下面给大家介绍SpringBoot参数间引用随机数设置的操作步骤,感兴趣的朋友一起看看吧
    2021-06-06
  • Spring Boot CLI安装教程

    Spring Boot CLI安装教程

    Spring Boot是一个命令行工具,用于使用Spring进行快速原型搭建。本文重点给大家介绍Spring Boot CLI安装教程,感兴趣的朋友参考下吧
    2017-08-08

最新评论