Use AES+Base64 encryption to encrypt, decrypt and resolve exceptions

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


/**
 * @author
 * 加密/解密 公共类
 */
@SuppressWarnings("restriction")
public class DESUtils 

    private static Key key; 
    private static String KEY_STR="mykey"; 
   
    static{ 

// There is no problem using this on the previous linux server, but the following exception occurs when my colleague deploys to the new linux server:

// java.lang.RuntimeException: javax.crypto.BadPaddingException: Invalid pad value!

// Cause analysis:

 

/* The implementation of SecureRandom  completely follows the internal state of the operating system itself, unless the caller calls the   setSeed method after calling the getInstance method  ; this implementation generates the same key every time on windows , but is different on solaris or some linux systems .         
*/

//        try 
//        { 
//            KeyGenerator generator = KeyGenerator.getInstance("DES"); 
//            SecureRandom secureRandom=SecureRandom.getInstance("SHA1PRNG"); 
//            secureRandom.setSeed(KEY_STR.getBytes()); 
//            generator.init(secureRandom); 
//            key = generator.generateKey(); 
//            generator=null; 
//        } 
//        catch (Exception e) 
//        { 
//            throw new RuntimeException(e); 
//        }

 

// After changing this, it is solved!
        try {
            KeyGenerator generator=KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(KEY_STR.getBytes());
            generator.init(128,secureRandom);
            key = generator. generateKey();
            generator=null;
          } catch (Exception e) {
              throw new RuntimeException("The initialization key is abnormal");
          }
       
    } 
     
    /**
     * Encrypt the string and return the encrypted string of BASE64
     * <Function details description>
     * @param str
     * @return
     * @see [class, class #method, class #member]
     */ 
    public static String getEncryptString(String str){ 
        BASE64Encoder base64Encoder = new BASE64Encoder(); 
        System.out.println(key); 
        try 
        { 
            byte[] strBytes = str.getBytes("UTF-8"); 
            Cipher cipher = Cipher.getInstance("AES"); 
            cipher.init(Cipher.ENCRYPT_MODE, key); 
            byte[] encryptStrBytes = cipher.doFinal(strBytes); 
            return base64Encoder.encode(encryptStrBytes); 
        } 
        catch (Exception e) 
        { 
            throw new RuntimeException(e); 
        } 
         
    } 
     
    /**
     * 对BASE64加密字符串进行解密
     * <功能详细描述>
     * @param str
     * @return
     * @see [类、类#方法、类#成员]
     */ 
    public static String getDecryptString(String str){ 
        BASE64Decoder base64Decoder = new BASE64Decoder(); 
        try 
        { 
            byte[] strBytes = base64Decoder.decodeBuffer(str); 
            Cipher cipher = Cipher.getInstance("AES"); 
            cipher.init(Cipher.DECRYPT_MODE, key); 
            byte[] encryptStrBytes = cipher.doFinal(strBytes); 
            return new String(encryptStrBytes,"UTF-8"); 
        } 
        catch (Exception e) 
        { 
            throw new RuntimeException(e); 
        } 
         
    } 
     
    //main test
// public static void main(String[] args) 
// { 
// String name="admin"; 
// String password="123456"; 

// String encryname = getEncryptString(name); 
/ / String encrypassword = getEncryptString(password); 
// System.out.println("Username encrypted:"+encryname); 
// System.out.println("Password encrypted:"+encrypassword); 
//         
// System.out.println("Username decrypted:"+getDecryptString(encryname)); 
// System.out.println("Password decrypted:"+getDecryptString(encrypassword)); 
// } 
}

 

===================================================================================

 

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * @author
 * Extend PropertyPlaceholderConfigurer to decrypt the encrypted properties in the prop file and submit them to Spring
 */
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer 

    //encryptPropNames stores the encrypted properties that need to be decrypted Attribute
    private String[] encryptPropNames = {"jdbc.username", "jdbc.password"}; 
     
    /*
     *Rewrite convertProperty to decrypt properties with encrypted features
     */
    @Override 
    protected String convertProperty(String propertyName, String propertyValue ) 
    { 
         
        //If the property is found in the encrypted property list 
        if (isEncryptProp(propertyName)) 
        { 
            String decryptValue = DESUtils.getDecryptString(propertyValue); 
            return decryptValue; 
        }else {
            return propertyValue; 
        } 
         
    } 
     
    /**
     * 判断属性值是否加密
     * @param propertyName
     * @return
     */
    private boolean isEncryptProp(String propertyName) 
    { 
        for (String encryptName : encryptPropNames) 
        { 
            if (encryptName.equals(propertyName)) 
            { 
                return true; 
            } 
        } 
        return false; 
    } 
}

 

 

===================================================================================

Add the following configuration to the spring.xml file:

<bean id="propertyConfig"    class="com.gdt.smart.modules.slms.util.EncryptPropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
 </bean>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327033903&siteId=291194637