Jasypt的StandardPBEByteEncryptor使用源碼解析
Jasypt
Jasypt即Java Simplified Encryption,它主要是簡化項目加解密的工作,內(nèi)置提供了很多組件的集成,比如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實現(xiàn)了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值是固定的和動態(tài)的,固定的則是初始化的時候就設(shè)置好的,直接從實例屬性取,然后直接調(diào)用cipher加密
而動態(tài)的話,則通過saltGenerator和generateIV來生成salt和iv,之后根據(jù)salt、iv和keyObtentionIterations來創(chuàng)建PBEParameterSpec,然后初始化cipher再進行加密
最后通過ivGenerator判斷是否需要把iv包含到加密結(jié)果中,是則append到前面進去,再通過saltGenerator判斷是否應(yīng)該把slat包含到加密結(jié)果中,是則append到前面進去,最后返回解密結(jié)果
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是否包含在密文中,是則根據(jù)配置的salt的長度從密文取出來salt,之后通過ivGenerator判斷iv是否包含在密文中,是則從剩下的密文取出來iv,得到slat和iv之后,對剩下的密文進行解密
小結(jié)
StandardPBEByteEncryptor實現(xiàn)了ByteEncryptor的encrypt和decrypt方法,其主要思路就是判斷slat、iv是否包含在密文,然后做對應(yīng)的處理。
doc Jasypt
以上就是Jasypt的StandardPBEByteEncryptor使用源碼解析的詳細內(nèi)容,更多關(guān)于Jasypt StandardPBEByteEncryptor的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Resilience4J通過yml設(shè)置circuitBreaker的方法
Resilience4j是一個輕量級、易于使用的容錯庫,其靈感來自Netflix Hystrix,但專為Java 8和函數(shù)式編程設(shè)計,這篇文章主要介紹了Resilience4J通過yml設(shè)置circuitBreaker的方法,需要的朋友可以參考下2022-10-10Spring?Boot項目啟動報錯Unable?to?start?web?server解決方法
這篇文章主要給大家介紹了關(guān)于Spring?Boot項目啟動報錯Unable?to?start?web?server的解決方法,錯誤內(nèi)容大概的意思是未能加載嵌入的供web應(yīng)用加載的空間,是因為缺少ServletWebServerFactorybean,需要的朋友可以參考下2024-07-07MyBatis-Plus多數(shù)據(jù)源的示例代碼
本文主要介紹了MyBatis-Plus多數(shù)據(jù)源的示例代碼,包括依賴配置、數(shù)據(jù)源配置、Mapper 和 Service 的定義,具有一定的參考價值,感興趣的可以了解一下2024-05-05Spring Boot + Mybatis-Plus實現(xiàn)多數(shù)據(jù)源的方法
這篇文章主要介紹了Spring Boot + Mybatis-Plus實現(xiàn)多數(shù)據(jù)源的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11