AES/GCM/NoPadding 方式加密

1.采用GCM方式加密

高级加密标准(AES)加密算法可以在各种模式下使用。某些组合不安全:

  • 电子密码本(ECB)模式:在给定密钥下,任何给定的明文块始终被加密为相同的密文块。因此,它不能很好地隐藏数据模式。从某种意义上说,它不提供严重的消息机密性,并且完全不建议在加密协议中使用它。
  • 具有PKCS#5填充(或PKCS#7)的密码块链接(CBC)易受填充oracle攻击。

在这两种情况下,都应首选无填充的Galois /计数器模式(GCM

2.方法

首先,由于java默认不支持GCM方式,所以需要修改java配置

在 jdk安装目录下( %JAVA_HOME%\jre\lib\security )修改 java.security 文件,将

security.provider.7=com.sun.security.sasl.Provider 

替换为

security.provider.7=org.bouncycastle.jce.provider.BouncyCastleProvider

然后编辑代码

//KEY_ALGORITHM = "AES";
//DEFAULT_CIPHER_ALGORITHM = "AES/GCM/NoPadding";
javax.crypto.spec.SecretKeySpec skeySpec = new javax.crypto.spec.SecretKeySpec(raw, KEY_ALGORITHM);  
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);   //"算法/模式/补码方式" 
IvParameterSpec IV = new IvParameterSpec(skeySpec.getEncoded(),0,16);
cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, skeySpec,IV);  

3.常见问题

main函数内运行正常,在其他类中调用失败。

解决方法:加上bcprov-jdk14-1.50.jar包,在使用加密方法的地方加上如下代码

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

4.完整代码


import javax.crypto.spec.IvParameterSpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jersey.core.util.Base64;

public class AESUtil
{
    
    private static final String KEY_ALGORITHM = "AES";

    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/GCM/NoPadding";
    
    private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);
    
    public static String AESEncrypt(String sSrc, String sKey,String charset)
    {

        if (sSrc == null || sSrc.length() == 0) {
            return sSrc;
        }
        
        try
        {
            //charset ="UTF-8"
            byte[] raw = null; 
            
            if (charset == null || "".equals(charset))
            {
                raw= sKey.getBytes();
            }
            else{
                raw= sKey.getBytes(charset);
            }
                        
            javax.crypto.spec.SecretKeySpec skeySpec = new javax.crypto.spec.SecretKeySpec(raw, KEY_ALGORITHM);  
            javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);   //"算法/模式/补码方式" 
            IvParameterSpec IV = new IvParameterSpec(skeySpec.getEncoded(),0,16);
            cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, skeySpec,IV);  
            byte[] encrypted;
            encrypted = cipher.doFinal(sSrc.getBytes(charset));
            String miwen = new String( Base64.encode(encrypted),charset);
            return miwen;
        }
        catch (Exception e)
        {
            logger.error("excute encode failed,error=", e);
        }
        return null;
    }
    
    
    public static String AESDecrypt(String sSrc, String sKey,String charset)
    {
        if (sSrc == null || sSrc.length() == 0) {
            return sSrc;
        }
        
        try
        {
            //charset ="UTF-8"
            byte[] raw = null; 
            
            if (charset == null || "".equals(charset))
            {
                raw= sKey.getBytes();
            }
            else{
                raw= sKey.getBytes(charset);
            }
            
            javax.crypto.spec.SecretKeySpec skeySpec = new javax.crypto.spec.SecretKeySpec(raw, KEY_ALGORITHM);  
            javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);  //"算法/模式/补码方式" 
            IvParameterSpec IV = new IvParameterSpec(skeySpec.getEncoded(),0,16);
            cipher.init(javax.crypto.Cipher.DECRYPT_MODE, skeySpec,IV );  
            byte[] encrypted1 = Base64.decode(sSrc);//先用base64解密  
            byte[] original = cipher.doFinal(encrypted1);  
            String originalString = new String(original,charset).trim();
            return originalString;
        }
        catch (Exception e)
        {
            logger.error("excute encode failed,error=", e);
        }
        return null;

    }
    
    public static void main(String[] args)
    {

        String data1 = "中文测试?》、/";
        //AES key 长度必须16位
        String miwen=AESEncrypt(data1,"ABCDEFGHJKLMNOPQ","UTF-8");
        System.out.println("新加密后内容: string:" + miwen);
        String originalString=AESDecrypt(miwen,"ABCDEFGHJKLMNOPQ","UTF-8");
        System.out.println("新解密后内容: string:" + originalString);
    }
}

 

你可能感兴趣的:(Java)