`

Security3DES

 
阅读更多
public class Security3DES {
	private static final String Algorithm = "DESede"; //定义 加密算法,可用 DES,DESede,Blowfish
	
	/**
	 * @Title: encryptData
	 * @Description: 加密
	 * @param cryptKey 密钥
	 * @param src
	 * @return
	 */
    public static byte[] encryptData(String cryptKey, byte[] src) {
       try {
            //添加新安全算法,如果用JCE就要把它添加进去
            //Security.addProvider(new com.sun.crypto.provider.SunJCE());
           
            SecretKey deskey = new SecretKeySpec(build3DesKey(cryptKey), Algorithm);
            Cipher cip = Cipher.getInstance(Algorithm);
            cip.init(Cipher.ENCRYPT_MODE, deskey);
            return cip.doFinal(src);
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }
    
    /**
     * @Title: decryptData
     * @Description: 解密
     * @param cryptKey 密钥
     * @param src
     * @return
     */
	public static byte[] decryptData(String cryptKey, byte[] src) {
		try {
			SecretKey deskey = new SecretKeySpec(build3DesKey(cryptKey),Algorithm);

			Cipher cip = Cipher.getInstance(Algorithm);
			cip.init(Cipher.DECRYPT_MODE, deskey);
			return cip.doFinal(src);
		} catch (java.security.NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}
    
	/**
	 * @Title: build3DesKey
	 * @Description: 将key转为24位byte
	 * @param keyStr
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException {
		byte[] key = new byte[24];
		byte[] temp = keyStr.getBytes("UTF-8");
		if (key.length > temp.length) {
			System.arraycopy(temp, 0, key, 0, temp.length);
		} else {
			System.arraycopy(temp, 0, key, 0, key.length);
		}
		return key;
	}
	
    public static void main(String[] args){
		try {
			String keyBytes = "012345678901234567890123";

			String szSrc = "This is a 3DES test. 测试";

			System.out.println("加密前的字符串:" + szSrc);

			byte[] encoded = encryptData(keyBytes, szSrc.getBytes());
			BASE64Encoder enc = new BASE64Encoder();
			String cipherString = enc.encode(encoded);
			System.out.println("加密后的字符串:" + cipherString);

			BASE64Decoder base64 = new BASE64Decoder();

			byte[] byStr = base64.decodeBuffer(cipherString);
			byte[] srcBytes = decryptData(keyBytes, byStr);
			System.out.println("解密后的字符串:" + (new String(srcBytes)));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics