安全问题1:

来源:互联网 发布:运用大数据成功的案例 编辑:程序博客网 时间:2024/06/05 04:19

https://www.ibm.com/developerworks/cn/java/j-lo-springsecurity/
Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分
用户认证
客户端:
用户登录:需要填写用户名,密码,如果在传输的过程中直接用明文,就恨可能被拦截,导致密码泄露,
也就是说,在客户端提交数据之前,应该对数据进行加密,然后在服务器接到加密后的密钥后,在根据解密规则进行解密。
然后 再把揭秘后的 密码 进行 md5 加密,最后和数据库中的数据进行比较。




另外数据库中的密码也应该是加密过的,并且是不可逆的加密(例如md5),防止数据库被攻破后密码全部泄漏。
另外用户名密码数据应该和用户的其他信息分割开来,这样在返回用户信息的时候,不用把用户名密码一起返回。


用户登录成功之后,生成一个用户credential ,可以存入缓存,  key = 用户ID + 设备ID + version  ,  credential = used +"|"+时间戳+“|”+随机数 ,
然后返回给客户端,以后客户端每次请求的时候都要带着这个 credential,


如果某个操作需要校验 用户的credential ,就查询一下缓存中是否有 信息,如果没有,让用户重新登录。


用户credential  信息 存在缓存里是有时间限制的,为了让用户不用频繁登录,我们可以开启一个保持登陆的接口,
这个接口里,可以在用户打开app 的时候调用一下,用来更新用户的认证信息。


还有一些配置信息,也可以提供一个接口,让用户打开app 的时候可以调用。




web 端:


登陆过程是一样的,而且认证信息 返回给客户端后,存储位置也一样,都是存储到了cookie 中。






总结:
用户认证和用户权限检查是两回事儿,所以设计起来应该是两个过滤器(拦截器)。
过滤器和拦截器的作用这里是一样的,就是在用户操作之前进行一些判断,只是实现机制不同,
拦截器 实现机制 是反射,过滤器是 函数回调。
过滤器 必须用于 servlet 容器项目,拦截器不是。




web 端 用户认证 阶段 做的事情:


1 从 请求的cookie 中 ,获取 服务器 返回的 认证信息(用户ID,当前时间,用户ID和当前时间的 加密串,给cookie设置有效时间,域名),如果没有,则 告诉用户需要登录,如果有,验证登录信息的准确性,如果不准确,返回给客户端,重新登录,如果准确,
根据用户ID查询 用户信息,如果可以查到,并且用户状态等都是OK 的,则 确定用户登录成功,把用户信息设置到请求的属性中。


2 权限校验:拦截器:


获取请求URL,如果url 在不需要校验权限的列表中,则校验通过,否则,从request 中获取用户信息,根据用户信息获取用户权限信息,
根据当前url 判断 访问资源需要的权限,如果这个权限 在用户拥有的权限列表中,
则代表用户可以访问,否则 用户 不可以访问。




加密算法总结:


AES DES 对称
RSA DSA  非对称。
sha 签名
md5 不可逆加密。
base64






/**
 *
 */


import com.movikr.v2.utils.commons.UtilString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


/**
 * COMMENT: 高级加密标准 AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据
 *
 */
public class UtilAES {


    private static final Logger LOGGER = LoggerFactory.getLogger(UtilAES.class);


    /**
     * 解密
     *
     * @param byteMi byte数组
     * @param strKey 密码
     * @return
     */
    public static byte[] decrypt(byte[] byteMi, String strKey){


        if(byteMi == null || strKey == null)
            return null;


        return aes(byteMi, strKey, Cipher.DECRYPT_MODE);
    }


    /**
     * 加密
     *
     * @param byteMi byte数组
     * @param strKey 密码
     * @return
     */
    public static byte[] encrypt(byte[] byteMi, String strKey) {
        if(byteMi == null || strKey == null)
            return null;
        return aes(byteMi, strKey, Cipher.ENCRYPT_MODE);
    }


    /**
     * 解密
     *
     * @param str 加密成16进制的字符串
     * @param strKey 密码
     * @return
     */
    public static String decrypt(String str, String strKey){


        if(str == null || strKey == null)
            return null;


        //将16进制字符串str转换成byte数组
        byte[] decryptFrom = UtilString.parseHexStr2Byte(str);
        byte[] decryptResult = aes(decryptFrom, strKey, Cipher.DECRYPT_MODE);
        return new String(decryptResult);
    }


    /**
     * 加密
     *
     * @param str 内容字符串
     * @param strKey 密码
     * @return
     */
    public static String encrypt(String str, String strKey){


        if(str == null || strKey == null)
            return null;


        byte[] encryptResult = aes(str.getBytes(), strKey, Cipher.ENCRYPT_MODE);


        //将byte数组转换成16进制字符串
        String encryptResultStr = UtilString.parseByte2HexStr(encryptResult);
        return encryptResultStr;
    }


    /**
     * 通过秘钥key生成SecretKey
     *
     * @param strKey 秘钥key
     * @return
     */
    private static SecretKey getKey(String strKey) {
        try {
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(strKey.getBytes());
            generator.init(128, secureRandom);
            return generator.generateKey();
        } catch (Exception e) {
            LOGGER.error("getKey 失败 : ", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 加密/解密
     *
     * @param bytes  需要加密的内容
     * @param password 加密密码
     * @param option 选项
     * @return
     */
    public static byte[] aes(byte[] bytes, String password, int option) {
        try {


            SecretKey secretKey = getKey(password);
            if(secretKey == null)
                return null;


            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(option, key);// 初始化
            byte[] result = cipher.doFinal(bytes);
            return result;
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("aes 失败 : ", e.getMessage());
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            LOGGER.error("aes 失败 : ", e.getMessage());
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            LOGGER.error("aes 失败 : ", e.getMessage());
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            LOGGER.error("aes 失败 : ", e.getMessage());
            e.printStackTrace();
        } catch (BadPaddingException e) {
            LOGGER.error("aes 失败 : ", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }






    public static void main(String[] args) {


        String content = "201408131304";
        String password = "2ce24c6bac8b226d2ce24c6bac8b226d";
        //加密
        System.out.println("加密前:" + content);
        String result = encrypt(content, password);
        System.out.println("加密后:" + result);
        //解密
        result = decrypt(result, password);
        System.out.println("解密后:" + result);
    }




}










import org.apache.commons.codec.binary.Base64;


/**
 * COMMENT: base64工具类 commons-codec封装工具类
 */
public final class UtilBase64 {


    /**
     * 加密字符串为byte数组
     * @param str 字符串
     * @return
     */
    public static byte[] encodeByte(String str) {
        if(str == null)
            return null;
        return Base64.encodeBase64(str.getBytes(), true);
    }


    /**
     * 加密byte数组为字符串
     * @param bytes 字符串
     * @return
     */
    public static String encode(byte[] bytes) {
        if(bytes == null)
            return null;
        byte[] b = Base64.encodeBase64(bytes, true);
        return new String(b);
    }


    /**
     * 加密字符串为字符串
     * @param str 字符串
     * @return
     */
    public static String encode(String str) {
        if(str == null)
            return null;
        return encode(str.getBytes());
    }


    /**
     * 解密字符串为byte数组
     * @param str 字符串
     * @return
     */
    public static byte[] decodeByte(String str) {
        if(str == null)
            return null;
        return Base64.decodeBase64(str.getBytes());
    }


    /**
     * 解密byte数组为字符串
     * @param bytes 字符串
     * @return
     */
    public static String decode(byte[] bytes) {
        if(bytes == null)
            return null;
        byte[] b = Base64.decodeBase64(bytes);
        return new String(b);
    }


    /**
     * 解密字符串为字符串
     * @param str 字符串
     * @return
     */
    public static String decode(String str) {
        if(str == null)
            return null;
        return decode(str.getBytes());
    }


    public static void main(String[] args) {


        String str = "1111111";


        String enStr = encode(str);


        System.out.println(enStr);
        System.out.println(decode(enStr));
    }


}








import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;


/**
 * COMMENT: 非对称加密算法
 * DES可以使用56位密钥,并且用64位分组加密和解密数据(该标准在最近已经被高级加密标准(AES)所取代)
 */
public class UtilDES {


    private static final Logger LOGGER = LoggerFactory.getLogger(UtilDES.class);


    private final static String DES = "DES";


    /**
     * 根据键值进行加密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     */
    public static String encrypt(String data, String key) {
        try{
            byte[] bt = encrypt(data.getBytes(), key.getBytes());
            String strs = new BASE64Encoder().encode(bt);
            return strs;
        }catch (Exception e){
            LOGGER.error("encrypt 失败 : " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据键值进行解密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     */
    public static String decrypt(String data, String key) {


        if (data == null)
            return null;
        try{
            byte[] buf = UtilBase64.decodeByte(data);
            byte[] bt = decrypt(buf, key.getBytes());
            return new String(bt);
        }catch (Exception e){
            LOGGER.error("decrypt 失败 : " + e.getMessage());
            e.printStackTrace();
        }
        return null;


    }


    /**
     * 根据键值进行加密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     */
    private static byte[] encrypt(byte[] data, byte[] key) {


        try{
            // 生成一个可信任的随机数源
            SecureRandom sr = new SecureRandom();


            // 从原始密钥数据创建DESKeySpec对象
            DESKeySpec dks = new DESKeySpec(key);


            // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            SecretKey securekey = keyFactory.generateSecret(dks);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance(DES);


            // 用密钥初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);


            return cipher.doFinal(data);
        }catch (Exception e){
            LOGGER.error("encrypt 失败 : " + e.getMessage());
            e.printStackTrace();
        }
        return null;


    }


    /**
     * 根据键值进行解密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     */
    private static byte[] decrypt(byte[] data, byte[] key) {


        try{
            // 生成一个可信任的随机数源
            SecureRandom sr = new SecureRandom();


            // 从原始密钥数据创建DESKeySpec对象
            DESKeySpec dks = new DESKeySpec(key);


            // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            SecretKey securekey = keyFactory.generateSecret(dks);


            // Cipher对象实际完成解密操作
            Cipher cipher = Cipher.getInstance(DES);


            // 用密钥初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, securekey, sr);


            return cipher.doFinal(data);
        }catch (Exception e){
            LOGGER.error("decrypt 失败 : " + e.getMessage());
            e.printStackTrace();
        }
        return null;


    }


    public static void main(String[] args) throws Exception {
        String data = "123 456";
        String key = "wang!@#$%111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111";
        System.err.println(encrypt(data, key));
        System.err.println(decrypt(encrypt(data, key), key));


    }


}






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


import java.security.*;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;


/**
 * COMMENT: DSA加密算法 需要公钥 私钥 签名验证
 * <p>
 *     1.私钥加密生成数字签名
 *     2.公钥验证数据及签名
 *     3.如果数据和签名不匹配则认为验证失败
 * </p>
 */
public class UtilDSA {


    private static final Logger LOGGER = LoggerFactory.getLogger(UtilDSA.class);


    public static final String ALGORITHM = "DSA";


    private static final int KEY_SIZE = 1024;


    private static final String DEFAULT_SEED = "0f22507a10bbddd07d8a3082122966e3";


    private static final String PUBLIC_KEY = "DSAPublicKey";


    private static final String PRIVATE_KEY = "DSAPrivateKey";


    /**
     * 用私钥对信息生成数字签名
     *
     * @param data       加密数据
     * @param privateKey 私钥
     * @return
     */
    public static String sign(byte[] data, String privateKey) {
        try{
            // 解密由base64编码的私钥
            byte[] keyBytes = UtilBase64.decodeByte(privateKey);


            // 构造PKCS8EncodedKeySpec对象
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);


            // KEY_ALGORITHM 指定的加密算法
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);


            // 取私钥匙对象
            PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);


            // 用私钥对信息生成数字签名
            Signature signature = Signature.getInstance(keyFactory.getAlgorithm());
            signature.initSign(priKey);
            signature.update(data);


            return UtilBase64.encode(signature.sign());
        }catch (Exception e){
            LOGGER.error("sign 失败 : " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 校验数字签名
     *
     * @param data      加密数据
     * @param publicKey 公钥
     * @param sign      数字签名
     * @return 校验成功返回true 失败返回false
     */
    public static boolean verify(byte[] data, String publicKey, String sign) {


        try {
            // 解密由base64编码的公钥
            byte[] keyBytes = UtilBase64.decodeByte(publicKey);


            // 构造X509EncodedKeySpec对象
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);


            // ALGORITHM 指定的加密算法
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);


            // 取公钥匙对象
            PublicKey pubKey = keyFactory.generatePublic(keySpec);


            Signature signature = Signature.getInstance(keyFactory.getAlgorithm());
            signature.initVerify(pubKey);
            signature.update(data);


            // 验证签名是否正常
            return signature.verify(UtilBase64.decodeByte(sign));
        }catch (Exception e){
            LOGGER.error("verify 失败 : " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 生成密钥
     *
     * @param seed 种子
     * @return 密钥对象
     * @throws Exception
     */
    public static Map<String, Object> initKey(String seed) {


        try{
            KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM);
            // 初始化随机产生器
            SecureRandom secureRandom = new SecureRandom();
            secureRandom.setSeed(seed.getBytes());
            keygen.initialize(KEY_SIZE, secureRandom);


            KeyPair keys = keygen.genKeyPair();


            DSAPublicKey publicKey = (DSAPublicKey) keys.getPublic();
            DSAPrivateKey privateKey = (DSAPrivateKey) keys.getPrivate();


            Map<String, Object> map = new HashMap<String, Object>(2);
            map.put(PUBLIC_KEY, publicKey);
            map.put(PRIVATE_KEY, privateKey);


            return map;
        }catch (Exception e){
            LOGGER.error("initKey 失败 : " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 默认生成密钥
     *
     * @return 密钥对象
     */
    public static Map<String, Object> initKey() {
        return initKey(DEFAULT_SEED);
    }


    /**
     * 取得私钥
     *
     * @param keyMap
     * @return
     */
    public static String getPrivateKey(Map<String, Object> keyMap) {


        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return UtilBase64.encode(key.getEncoded());
    }


    /**
     * 取得公钥
     *
     * @param keyMap
     * @return
     */
    public static String getPublicKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return UtilBase64.encode(key.getEncoded());
    }


    public static void main(String[] args) {


        String inputStr = "abc";
        byte[] data = inputStr.getBytes();


        // 构建密钥
        Map<String, Object> keyMap = UtilDSA.initKey();


        // 获得密钥
        String publicKey = UtilDSA.getPublicKey(keyMap);
        String privateKey = UtilDSA.getPrivateKey(keyMap);


        System.out.println("公钥:\r" + publicKey);
        System.out.println("私钥:\r" + privateKey);


        // 产生签名
        String sign = UtilDSA.sign(data, privateKey);
        System.out.println("签名:\r" + sign);


        // 验证签名
        boolean status = UtilDSA.verify(data, publicKey, sign);
        System.out.println("状态:\r" + status);


    }


}








/**
 *
 */


import org.apache.commons.codec.digest.DigestUtils;


/**
 * USER:    samson
 * TIME:    2015-08-31 17:46
 * COMMENT: md5工具类 commons-codec封装工具类
 */
public class UtilMD5 {


    /**
     * md5 加密
     * @param bytes byte数组
     * @return
     */
    public static String MD5(byte[] bytes){
        if(bytes == null)
            return null;
        return DigestUtils.md5Hex(bytes);
    }




    /**
     * md5 加密
     * @param str 字符串
     * @return
     */
    public static String MD5(String str){
        if(str == null)
            return null;
        return DigestUtils.md5Hex(str);
    }


    public static void main(String[] args) {
        //96e79218965eb72c92a549dd5a330112
        System.out.println(MD5("111111"));
    }
}




/**
 *
 */


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;


/**
 * COMMENT: RSA加密算法是一种[非对称]加密算法
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式
 * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,
 * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
 * RSA加密明文最大长度117字节,解密要求密文最大长度为128字节,所以在加密和解密的过程中需要分块进行。
 * RSA加密对明文的长度是有限制的,如果加密数据过大会抛出如下异常
 * javax.crypto.IllegalBlockSizeException Data must not be longer than 117 bytes
 * <p>
 * rsa是公钥加密,速度慢,只能处理少量数据,优点是公钥即使在不安全的网络上公开,也能保证安全
 * 常见情况是双方用rsa协商出一个密钥后通过aes/3des给数据加密
 * </p>
 * <p>
 * 服务端生成RSA密钥对,将其中的RSA公钥传递给客户端,然后用RSA密钥对AES密钥加密,传递给客户端,
 * 客户端用RSA公钥解密后,得到AES密钥,最后使用AES密钥跟服务端互通数据。
 * </p>
 * <p>
 * //利用rsa和aes算法 与客户端交互
 * //1.aes利用key加密content 为 aes_content   rsa利用公钥加密aes key 为 rsa_aes_key
 * //2.传输rsa_aes_key和aes_content
 * //3.保存在客户端
 * //4.返回服务器rsa_aes_key和aes_content
 * //5.rsa利用私钥解密 rsa_aes_key 为 key
 * //6.aes利用可以解密 aes_content
 * //获取rsa公钥
 * Map<String, Object> keyMap = UtilRSA.genKeyPair();
 * String publicKey = UtilRSA.getPublicKey(keyMap);
 * String privateKey = UtilRSA.getPrivateKey(keyMap);
 * <p>
 * String aesKey = "12345678";
 * byte[] aesKeyEncodeByRsa = encodeByPubKeyRSAAES(publicKey, aesKey.getBytes());
 * <p>
 * String content = "hello world";
 * String contentEncodeByAes = UtilAES.encryptStr(content, aesKey);
 * System.out.println(contentEncodeByAes);
 * <p>
 * byte[] aesKeyDecodeByRsa = decodeByPubKeyRSAAES(privateKey, aesKeyEncodeByRsa);
 * String aesKeyDecodeByRsaStr = new String(aesKeyDecodeByRsa);
 * String contentDecodeByAes = UtilAES.decryptStr(contentEncodeByAes, aesKeyDecodeByRsaStr);
 * System.out.println(contentDecodeByAes);
 * </p>
 */
public class UtilRSA {


    private static final Logger LOGGER = LoggerFactory.getLogger(UtilRSA.class);


    //加密算法RSA
    public static final String KEY_ALGORITHM = "RSA";


    //签名算法
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";


    //获取公钥的key
    private static final String PUBLIC_KEY = "RSAPublicKey";


    //获取私钥的key
    private static final String PRIVATE_KEY = "RSAPrivateKey";


    //RSA最大加密明文大小
    private static final int MAX_ENCRYPT_BLOCK = 117;


    //RSA最大解密密文大小
    private static final int MAX_DECRYPT_BLOCK = 128;


    /**
     * 生成密钥对(公钥和私钥)
     *
     * @return
     */
    public static Map<String, Object> genKeyPair() {


        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGen.initialize(1024);
            KeyPair keyPair = keyPairGen.generateKeyPair();
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            Map<String, Object> keyMap = new HashMap<String, Object>(2);
            keyMap.put(PUBLIC_KEY, publicKey);
            keyMap.put(PRIVATE_KEY, privateKey);
            return keyMap;
        } catch (Exception e) {
            LOGGER.error("genKeyPair 失败 : " + e.getMessage());
            e.printStackTrace();
        }


        return null;


    }


    /**
     * 获取私钥
     *
     * @param keyMap 密钥对
     * @return
     */
    public static String getPrivateKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return UtilBase64.encode(key.getEncoded());
    }


    /**
     * 获取公钥
     *
     * @param keyMap 密钥对
     * @return
     */
    public static String getPublicKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return UtilBase64.encode(key.getEncoded());
    }


    /**
     * 用私钥对信息生成数字签名
     *
     * @param data       已加密数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     */
    public static String sign(byte[] data, String privateKey) {


        try {
            byte[] keyBytes = UtilBase64.decodeByte(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(privateK);
            signature.update(data);
            return UtilBase64.encode(signature.sign());
        } catch (Exception e) {
            LOGGER.error("sign 失败 : " + e.getMessage());
            e.printStackTrace();
        }


        return null;


    }


    /**
     * 校验数字签名
     *
     * @param data      已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @param sign      数字签名
     * @return
     */
    public static boolean verify(byte[] data, String publicKey, String sign) {


        try {
            byte[] keyBytes = UtilBase64.decodeByte(publicKey);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicK = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(publicK);
            signature.update(data);
            return signature.verify(UtilBase64.decodeByte(sign));
        } catch (Exception e) {
            LOGGER.error("verify 失败 : " + e.getMessage());
            e.printStackTrace();
        }


        return false;


    }


    /**
     * 私钥解密
     *
     * @param encryptedData 已加密数据
     * @param privateKey    私钥(BASE64编码)
     * @return
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) {


        try {
            byte[] keyBytes = UtilBase64.decodeByte(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateK);
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            return decryptedData;
        } catch (Exception e) {
            LOGGER.error("decryptByPrivateKey 失败 : " + e.getMessage());
            e.printStackTrace();
        }


        return null;


    }


    /**
     * 公钥解密
     *
     * @param encryptedData 已加密数据
     * @param publicKey     公钥(BASE64编码)
     * @return
     */
    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) {
        try {
            byte[] keyBytes = UtilBase64.decodeByte(publicKey);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicK);
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            return decryptedData;
        } catch (Exception e) {
            LOGGER.error("decryptByPublicKey 失败 : " + e.getMessage());
            e.printStackTrace();
        }


        return null;


    }


    /**
     * 公钥加密
     *
     * @param data      源数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey) {
        try {


            byte[] keyBytes = UtilBase64.decodeByte(publicKey);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            // 对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicK);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encryptedData;


        } catch (Exception e) {
            LOGGER.error("encryptByPublicKey 失败 : " + e.getMessage());
            e.printStackTrace();
        }


        return null;
    }


    /**
     * 私钥加密
     *
     * @param data       源数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     */
    public static byte[] encryptByPrivateKey(byte[] data, String privateKey) {
        try {


            byte[] keyBytes = UtilBase64.decodeByte(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateK);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encryptedData;


        } catch (Exception e) {
            LOGGER.error("encryptByPrivateKey 失败 : " + e.getMessage());
            e.printStackTrace();
        }


        return null;
    }




    public static void main(String[] args) throws UnsupportedEncodingException {


//        Map<String, Object> keyMap = UtilRSA.genKeyPair();
//        String publicKey = UtilRSA.getPublicKey(keyMap);
//        String privateKey = UtilRSA.getPrivateKey(keyMap);
//        System.out.println("公钥: \n\r" + publicKey);
//        System.out.println("私钥: \n\r" + privateKey);
//
//        System.out.println("公钥加密——私钥解密");
//        String source = "这是一行没有任何意义的文字,你看完了等于没看,不是吗?这是一行没有任何意义的文字,";
//        System.out.println("\r加密前文字:\r\n" + source);
//        byte[] data = source.getBytes();
//        byte[] encodedData = UtilRSA.encryptByPublicKey(data, publicKey);
//        System.out.println("加密后文字:\r\n" + new String(encodedData));
//        byte[] decodedData = UtilRSA.decryptByPrivateKey(encodedData, privateKey);
//        String target = new String(decodedData);
//        System.out.println("解密后文字: \r\n" + target);
//
//
////        byte[] data2 = source.getBytes();
////        byte[] encodedData2 = UtilRSA.rsa(data2, (Key)keyMap.get(PUBLIC_KEY), Cipher.ENCRYPT_MODE);
////        System.out.println("加密后文字++++++++:\r\n" + new String(encodedData2));
////        byte[] decodedData2 = UtilRSA.rsa(encodedData2, (Key) keyMap.get(PRIVATE_KEY), Cipher.DECRYPT_MODE);
////        String target2 = new String(decodedData2);
////        System.out.println("解密后文字+++++++++: \r\n" + target2);
//
//        ////////////////////////////////////////////////
//
//        System.out.println("私钥加密——公钥解密");
//        String source1 = "这是一行测试RSA数字签名的无意义文字";
//        System.out.println("原文字:\r\n" + source);
//        byte[] data1 = source1.getBytes();
//        byte[] encodedData1 = UtilRSA.encryptByPrivateKey(data1, privateKey);
//        System.out.println("加密后:\r\n" + new String(encodedData1));
//        byte[] decodedData1 = UtilRSA.decryptByPublicKey(encodedData1, publicKey);
//        String target1 = new String(decodedData1);
//        System.out.println("解密后: \r\n" + target1);
//        System.out.println("私钥签名——公钥验证签名");
//        String sign = UtilRSA.sign(encodedData1, privateKey);
//        System.out.println("签名:\r" + sign);
//        boolean status = UtilRSA.verify(encodedData1, publicKey, sign);
//        System.out.println("验证结果:\r" + status);


        ///////////////////////////////////////////////////////////////////////////


        //客户端与服务器端约定部分 生成rsa 私有key 和 公共key
        Map<String, Object> keyMap = UtilRSA.genKeyPair();
        String publicKey = UtilRSA.getPublicKey(keyMap);
        String privateKey = UtilRSA.getPrivateKey(keyMap);


        //客户端部分
        //生成随机aeskey 通过 aeskey加密内容 通过 rsa公钥加密asekey 发送 aeskey加密后的内容 和
        //rsa公钥加密后的aeskey(通过base64加密成字符串) 到 服务器
        //添加一个版本号 便于服务修改后判断
        String aesKey = "12345678";
        byte[] aesKeyEncodeByRsa = encryptByPublicKey(aesKey.getBytes(), publicKey);
        String content = "hello world";
        String contentEncodeByAes = UtilAES.encrypt(content, aesKey);
        String version = "10000";
        String aesKeyEncodeByRsaStr = version + UtilBase64.encode(aesKeyEncodeByRsa);
        System.out.println(aesKeyEncodeByRsaStr + " " + contentEncodeByAes);


        //服务器端部分
        //通过 rsa私钥解密(rsa公钥加密后的aeskey base64加密串) 得到 aeskey 通过 aeskey 解密 (aeskey加密内容) 得到 内容
        String getVersion = aesKeyEncodeByRsaStr.substring(0, 5);
        if(!StringUtils.equals(version, getVersion)){
            System.out.println("版本号发生改变!");
        }
        byte[] aesKey_ = UtilBase64.decodeByte(aesKeyEncodeByRsaStr.substring(5, aesKeyEncodeByRsaStr.length()));
        byte[] aesKeyDecodeByRsa = decryptByPrivateKey(aesKey_, privateKey);
        String aesKeyDecodeByRsaStr = new String(aesKeyDecodeByRsa);
        String contentDecodeByAes = UtilAES.decrypt(contentEncodeByAes, aesKeyDecodeByRsaStr);
        System.out.println(contentDecodeByAes);


    }




}










import org.apache.commons.codec.digest.DigestUtils;


/**
 * COMMENT: sha1工具类 commons-codec封装工具类
 * 安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准 (Digital Signature Standard DSS)
 * 里面定义的数字签名算法(Digital Signature Algorithm DSA)
 */
public class UtilSha1 {


    /**
     * sha1加密
     *
     * @param str 加密字符串
     * @return
     */
    public static String Sha1(String str) {
        if (str == null)
            return null;
        return DigestUtils.shaHex(str);
    }


    /**
     * @param args
     */
    public static void main(String[] args) {


        System.out.println(UtilSha1.Sha1("我们"));
        System.out.println(UtilSha1.Sha1(""));
    }


}












用户授权:请参考:
JavaWeb 案例——访问权限控制1
在filter 中无法通过依赖注入,注入功能组件,但是 可以 通过 工具类 SpringContextHolder 来获取某个组件类。
CookieService cookieService = SpringContextHolder.getBean("cookieService");
java 代码:
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {


    private static ApplicationContext applicationContext = null;


    private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);


    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }


    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }


    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> Map<String, T> getBean(Class<T> requiredType) {
        assertContextInjected();
        return applicationContext.getBeansOfType(requiredType);
    }


    /**
     * 清除SpringContextHolder中的ApplicationContext为Null.
     */
    public static void clearHolder() {
        logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
        applicationContext = null;


    }


    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中.
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        logger.debug("注入ApplicationContext到SpringContextHolder:" + applicationContext);


        if (SpringContextHolder.applicationContext != null) {
            logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
        }


        SpringContextHolder.applicationContext = applicationContext; // NOSONAR
    }


    /**
     * 实现DisposableBean接口, 在Context关闭时清理静态变量.
     */
    public void destroy() throws Exception {
        SpringContextHolder.clearHolder();
    }


    /**
     * 检查ApplicationContext不为空.
     */
    private static void assertContextInjected() {
        Assert.state(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
    }


}


spring 配置文件:
<bean class="com.movie.m.core.spring.SpringContextHolder" lazy-init="false" />


那applicationContext 是如何被设置到 SpringContextHolder  中的呢?


可以看到 ApplicationContextAware 继承了 ApplicationContextAware 接口,
这个接口中只有一个方法:setApplicationContext(ApplicationContext applicationContext) ;
继承了这个接口 就代表,当 ApplicationContext 加载完毕后,就会调用这个方法。这样这个类就有了applicationContext 属性。




0 0
原创粉丝点击