2015-05-28 16:01:41 iteye_20793 阅读数 60
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25337 人正在学习 去看看 邵发

参考地址:

 

1,DES加密解密(适用Windows和Linux系统)防止linux下解密失败

2,

解决Linux操作系统下AES解密失败的问题

 

原因分析:

 

SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在调用 getInstance 方法之后又调用了 setSeed 方法;该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。
2017-03-24 10:58:57 u014520797 阅读数 2834
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25337 人正在学习 去看看 邵发

1、报错内容

avax.crypto.BadPaddingException: Given final block not properly padded
	at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:810)
	at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:675)
	at com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:314)
	at javax.crypto.Cipher.doFinal(Cipher.java:1976)


2、

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

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

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



public class DesEncryptUtil {

    private  Key key;

    public DesEncryptUtil() {
    	setKey2("hahhah");
	}
    /**
     * 根据参数生成KEY
     * 
     * @param strKey
     * 
     * Windows下正常  Linux 下报错
     */
    public void setKey(String strKey) {
        try {
            KeyGenerator _generator = KeyGenerator.getInstance("DES");
            _generator.init(new SecureRandom(strKey.getBytes()));
             this.key = _generator.generateKey();
            _generator = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    //Linux 系统下正常运行
    public void setKey2(String strKey) {
        try {
		    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
		    DESKeySpec keySpec = new DESKeySpec(strKey.getBytes("utf-8"));  
		    this.key = keyFactory.generateSecret(keySpec);  
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
        	
        }
    }
    
    public static void main(String[] args) {
    	

    	DesEncryptUtil u = new DesEncryptUtil();    
    	for (int i = 1; i < 100; i++) {
    		//加密
    		String encString = u.getEncString(""+i);
    		//解密
    		String desString = u.getDesString(encString);
    		System.err.println("encString:"+encString+";desString:"+desString+":"+i);
    		if (!desString.equals(""+i)) {
    			System.err.println(i+":错误:encString:"+encString+";desString:"+desString);
			}
		}
	}
    
    /**
     * 加密String明文输入,String密文输出
     * 
     * @param strMing
     * @return 加密
     */
    public String getEncString(String strMing) {
        byte[] byteMi = null;
        byte[] byteMing = null;
        String strMi = "";
        BASE64Encoder base64en = new BASE64Encoder();
        try {
            byteMing = strMing.getBytes("UTF-8");
            byteMi = getEncCode(byteMing);
            strMi = base64en.encode(byteMi);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            base64en = null;
            byteMing = null;
            byteMi = null;
        }
        return strMi;
    }

    /**
     * 解密 以String密文输入,String明文输出
     * 
     * @param strMi
     * @return 解密
     */
    public String getDesString(String strMi) {
        BASE64Decoder base64De = new BASE64Decoder();
        byte[] byteMing = null;
        byte[] byteMi = null;
        String strMing = "";
        try {
            byteMi = base64De.decodeBuffer(strMi);
            byteMing = getDesCode(byteMi);
            strMing = new String(byteMing, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            base64De = null;
            byteMing = null;
            byteMi = null;
        }
        return strMing;
    }

    /**
     * 加密以byte[]明文输入,byte[]密文输出
     * 
     * @param byteS
     * @return
     */
    private  byte[] getEncCode(byte[] byteS) {
        byte[] byteFina = null;
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byteFina = cipher.doFinal(byteS);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cipher = null;
        }
        return byteFina;
    }

    /**
     * 解密以byte[]密文输入,以byte[]明文输出
     * 
     * @param byteD
     * @return
     */
    private byte[] getDesCode(byte[] byteD) {
        Cipher cipher;
        byte[] byteFina = null;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, this.key);
            byteFina = cipher.doFinal(byteD);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cipher = null;
        }
        return byteFina;
    }
    
    
}


3、解释 ,所以setKey时  用 //Linux 系统下  public void setKey2(String strKey) {}方法
  

 * SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在调用 getInstance 方法,然后调用 setSeed 方法;
     * 该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。
     * 关于SecureRandom类的详细介绍,见 http://yangzb.iteye.com/blog/325264



参考:

http://blog.csdn.net/rj042/article/details/8196125

http://www.cnblogs.com/digdeep/p/5580244.html

2018-06-05 09:54:20 semial 阅读数 568
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25337 人正在学习 去看看 邵发
不同则关于的SecureRandom的类的详细介绍,见  http://yangzb.iteye.com/blog/325264            

package com.avic.controller.user.utls;


import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


import org.apache.commons.lang3.StringUtils;


public class DESEncrypt {
private static final String DES_ALGORITHM = "DES";
private static final DESEncrypt desEncrypt = new DESEncrypt();


private DESEncrypt() {
}


public static DESEncrypt getInstance() {
return desEncrypt;
}


/**
* DES加密
* 
* @param plainData
* @param secretKey
* @return
* @throws Exception
*/
public String createSign(Map<String, Object> params, boolean encode, String secretKey) throws Exception {


Cipher cipher = null;
try {
cipher = Cipher.getInstance(DES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, generateKey1(secretKey));


} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {


}


try {
// 为了防止解密时报javax.crypto.IllegalBlockSizeException: Input length must
// be multiple of 8 when decrypting with padded cipher异常,
// 不能把加密后的字节数组直接转换成字符串
Set<String> keysSet = params.keySet();
Object[] keys = keysSet.toArray();
Arrays.sort(keys);
StringBuffer temp = new StringBuffer();
boolean first = true;
for (Object key : keys) {
if (first) {
first = false;
} else {
temp.append("&");
}
temp.append(key).append("=");
Object value = params.get(key);
String valueString = "";
if (null != value) {
valueString = String.valueOf(value);
}
if (encode) {
temp.append(URLEncoder.encode(valueString, "UTF-8"));
} else {
temp.append(valueString);
}
}


byte[] buf = cipher.doFinal(String.valueOf(temp).getBytes());


return Base64Utils.encode(buf);


} catch (IllegalBlockSizeException e) {
e.printStackTrace();
throw new Exception("IllegalBlockSizeException", e);
} catch (BadPaddingException e) {
e.printStackTrace();
throw new Exception("BadPaddingException", e);
}


}


/**
* DES解密
* 
* @param secretData
* @param secretKey
* @return
* @throws Exception
*/
public Map<String, Object> resolveSign(String secretData, String secretKey) throws Exception {


Cipher cipher = null;
try {
cipher = Cipher.getInstance(DES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, generateKey1(secretKey));


} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new Exception("NoSuchAlgorithmException", e);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
throw new Exception("NoSuchPaddingException", e);
} catch (InvalidKeyException e) {
e.printStackTrace();
throw new Exception("InvalidKeyException", e);


}
try {
Map<String, Object> ret = new HashMap<String, Object>();
byte[] buf = cipher.doFinal(Base64Utils.decode(secretData.toCharArray()));


String[] params = new String(buf).split("&");
for (int i = 0; i < params.length; i++) {
String[] param = params[i].split("=");
if (StringUtils.isNotBlank(param[0])) {
if (param.length > 1) {
ret.put(param[0], param[1]);
} else {
ret.put(param[0], "");
}
}


}
return ret;


} catch (IllegalBlockSizeException e) {
e.printStackTrace();
throw new Exception("IllegalBlockSizeException", e);
} catch (BadPaddingException e) {
e.printStackTrace();
throw new Exception("BadPaddingException", e);
}
}


/**
* 获得秘密密钥
* 
* @param secretKey
* @return
* @throws NoSuchAlgorithmException
*/
private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException {
SecureRandom secureRandom = new SecureRandom(secretKey.getBytes());


// 为我们选择的DES算法生成一个KeyGenerator对象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(DES_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
}
kg.init(secureRandom);
// kg.init(56, secureRandom);


// 生成密钥
return kg.generateKey();
}


/**
* 获得密钥
* 
* @param secretKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws InvalidKeySpecException
*/
private SecretKey generateKey1(String secretKey)
throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {


SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes());
keyFactory.generateSecret(keySpec);
return keyFactory.generateSecret(keySpec);
}


public static void main(String[] a) throws Exception {
String input = "cy11Xlbrmzyh:604:301:1353064296";
String key = "1111111";


// DESEncrypt des = new DESEncrypt();
Map<String, Object> params = new HashMap<String, Object>();
params.put("norce", Math.random());
params.put("userId", 11);
params.put("userName", "aaaaa");
params.put("createTime", new Date());
String result = DESEncrypt.getInstance().createSign(params, false, key);
System.out.println(result);


System.out.println(DESEncrypt.getInstance().resolveSign(result, key));


}


static class Base64Utils {


static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
.toCharArray();
static private byte[] codes = new byte[256];
static {
for (int i = 0; i < 256; i++)
codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
codes[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++)
codes[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++)
codes[i] = (byte) (52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}


/**
* 将原始数据编码为base64编码
*/
static public String encode(byte[] data) {
char[] out = new char[((data.length + 2) / 3) * 4];
for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
boolean quad = false;
boolean trip = false;
int val = (0xFF & (int) data[i]);
val <<= 8;
if ((i + 1) < data.length) {
val |= (0xFF & (int) data[i + 1]);
trip = true;
}
val <<= 8;
if ((i + 2) < data.length) {
val |= (0xFF & (int) data[i + 2]);
quad = true;
}
out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 1] = alphabet[val & 0x3F];
val >>= 6;
out[index + 0] = alphabet[val & 0x3F];
}


return new String(out);
}


/**
* 将base64编码的数据解码成原始数据
*/
static public byte[] decode(char[] data) {
int len = ((data.length + 3) / 4) * 3;
if (data.length > 0 && data[data.length - 1] == '=')
--len;
if (data.length > 1 && data[data.length - 2] == '=')
--len;
byte[] out = new byte[len];
int shift = 0;
int accum = 0;
int index = 0;
for (int ix = 0; ix < data.length; ix++) {
int value = codes[data[ix] & 0xFF];
if (value >= 0) {
accum <<= 6;
shift += 6;
accum |= value;
if (shift >= 8) {
shift -= 8;
out[index++] = (byte) ((accum >> shift) & 0xff);
}
}
}
if (index != out.length)
throw new Error("miscalculated data length!");
return out;
}
}
}





DES加密解密(适用的的Windows和Linux系统),防止Linux的的下解密失败工具类可以此链接下载工具类https://download.csdn.net/download/semial/10477883

 

2019-01-22 11:42:20 spark_guo 阅读数 232
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25337 人正在学习 去看看 邵发

package com.abc.core.utils;


import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


/**
 * 将数据使用DES算法加密,再进行base64编码,方便进行网络传输,支持中文。
 * @author Administrator
 */
public class CipherBase64 {
    @SuppressWarnings("unused")
    private static Logger logger =LogManager.getLogger(CipherBase64.class);
    
    private Key key;
    private Cipher cipher;
    private static CipherBase64 singltonEncrypt = null;
    private static CipherBase64 singltonDecrypt = null;
    
    @SuppressWarnings("unused")
    private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
        .toCharArray();

    private byte[] codes = new byte[256];    
    
    /**
     * 
     * 初始化,由于消耗内存过多,所以设置为private,只能用getInstance()方法生成一个对象
     * 
     */
    private CipherBase64(String model) {
        for (int i = 0; i < 256; i++)
            codes[i] = -1;
        for (int i = 'A'; i <= 'Z'; i++)
            codes[i] = (byte) (i - 'A');
        for (int i = 'a'; i <= 'z'; i++)
            codes[i] = (byte) (26 + i - 'a');
        for (int i = '0'; i <= '9'; i++)
            codes[i] = (byte) (52 + i - '0');
        codes['+'] = 62;
        codes['/'] = 63;
        try {
            cipher = Cipher.getInstance(model);
        } catch (NoSuchAlgorithmException e) {
            singltonEncrypt = null;
            singltonDecrypt = null;
            logger.error(e.getMessage(), e);
        } catch (NoSuchPaddingException e) {
            singltonEncrypt = null;
            singltonDecrypt = null;
            logger.error(e.getMessage(), e);
        }
    }

    public static CipherBase64 getSingltonDecryptInstance() throws InvalidKeyException {
           if (singltonDecrypt == null) {
                synchronized (CipherBase64.class) {
                    if (singltonDecrypt == null) {
                        CipherBase64 cipherBase = new CipherBase64("DES/ECB/NoPadding");
                        cipherBase.setKey(SystemParaUtil.SECRET_KEY);
                        cipherBase.initDecrypt();
                        singltonDecrypt = cipherBase;
                    }
                }
            }

        return singltonDecrypt;
    }

    public static CipherBase64 getSingltonEncryptInstance() throws InvalidKeyException {
           if (singltonEncrypt == null) {
                synchronized (CipherBase64.class) {
                    if (singltonEncrypt == null) {
                        CipherBase64 cipherBase = new CipherBase64("DES");
                        cipherBase.setKey(SystemParaUtil.SECRET_KEY);
                        cipherBase.initEncrypt();
                        singltonEncrypt = cipherBase;
                    }
                }
            }
           
        
        return singltonEncrypt;
    }
    /**
     * 
     * 
     * 加密
     * @param sourceString
     * @return
     * @throws InvalidKeyException
     * @throws UnsupportedEncodingException
     * @throws IllegalStateException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    private String encrpt(String sourceString) throws InvalidKeyException,
            UnsupportedEncodingException, IllegalStateException,
            IllegalBlockSizeException, BadPaddingException {
        String cryptedString = null;
        int cypheredBytes = 0;
        byte[] inputBytes = sourceString.getBytes("GBK");
        byte[] outputBytes = new byte[256];
        while (true) {
            try {
                cypheredBytes = cipher.doFinal(inputBytes, 0,
                        inputBytes.length, outputBytes, 0);
                break;
            } catch (ShortBufferException e) {
                outputBytes = new byte[outputBytes.length * 2];
            }
        }
        cryptedString = new String(outputBytes, 0, cypheredBytes, "iso-8859-1");
        return cryptedString;
    }

    /**
     * 
     * 解密
     * @param sourcebyte
     * @return
     * @throws InvalidKeyException
     * @throws UnsupportedEncodingException
     * @throws IllegalStateException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    private String decrypt(byte[] sourcebyte) throws InvalidKeyException,
            UnsupportedEncodingException, IllegalStateException,
            IllegalBlockSizeException, BadPaddingException{
        if(sourcebyte == null || sourcebyte.length == 0){
            throw new IllegalBlockSizeException("sourcebyte length equals 0");
        }
        String cryptedString = null;
        int cypheredBytes = 0;
        byte[] inputBytes = sourcebyte;
        byte[] outputBytes = new byte[256];
        while (true) {
            try {
                cypheredBytes = cipher.doFinal(inputBytes, 0,
                        inputBytes.length, outputBytes, 0);
                break;
            } catch (ShortBufferException e) {
                outputBytes = new byte[outputBytes.length * 2];
            }
        }
        cryptedString = new String(outputBytes, 0, cypheredBytes, "GBK");
        return cryptedString;
    }
    
    public String encrpts(String string) throws InvalidKeyException,
            UnsupportedEncodingException, IllegalStateException,
            IllegalBlockSizeException, BadPaddingException {        
        return SimpleCrypto.toHex(encrpt(string));
    }

    public String decrypts(String string) throws InvalidKeyException,
            UnsupportedEncodingException, IllegalStateException,
            IllegalBlockSizeException, BadPaddingException, Exception {
        return decrypt(SimpleCrypto.toByte(string));
    }
    
    /**
     * 设置密钥
     * @param keyString
     */
    private void setKey(String keyString) {
        byte[] keyData = keyString.getBytes();
        key = new SecretKeySpec(keyData, 0, keyData.length, "DES");
    }

    private void initDecrypt() throws InvalidKeyException {
        cipher.init(Cipher.DECRYPT_MODE, key);
    }

    private void initEncrypt() throws InvalidKeyException {
        cipher.init(Cipher.ENCRYPT_MODE, key);
    }
}
注意点:
(1)加密获取实例:DES,因为DES就是:DES/ECB/PKCS5Padding,默认的加密算法
(2)解密获取实例:DES/ECB/NoPadding
(3)加密前,会使用默认的空格填充,解密的时候要去空格。

2010-07-21 16:42:00 hbcui1984 阅读数 14280
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25337 人正在学习 去看看 邵发

 

现象描述:
windows上加解密正常,linux上加密正常,解密时发生如下异常

javax.crypto.BadPaddingException: Given final block not properly padded

       at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
       at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
       at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
       at javax.crypto.Cipher.doFinal(DashoA13*..)
       at chb.test.crypto.AESUtils.crypt(AESUtils.java:386)
       at chb.test.crypto.AESUtils.AesDecrypt(AESUtils.java:254)
       at chb.test.crypto.AESUtils.main(AESUtils.java:40) 

解决方法:
经过检查之后,定位在生成KEY的方法上,如下:
修改到如下方式,问题解决:


原因分析

SecureRandom 实现完全隨操作系统本身的內部狀態,除非調用方在調用 getInstance 方法之後又調用了 setSeed 方法;该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。

 

没有更多推荐了,返回首页