加密算法



加密:
public byte[] encrypt(String input) { try { byte[] aesKey128 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
       SecretKey secKey = new SecretKeySpec(aesKey128, "AES"); byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; IvParameterSpec ivAlgorithParam = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secKey, ivAlgorithParam); return cipher.doFinal(input.getBytes()); } catch (Exception e) { e.printStackTrace(); } return null; } 解密: public String decrypt(byte[] input) { try { byte[] aesKey128 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; SecretKey secKey = new SecretKeySpec(aesKey128, "AES"); byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; IvParameterSpec ivAlgorithParam = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secKey, ivAlgorithParam); return new String(cipher.doFinal(input)); } catch (Exception e) { e.printStackTrace(); } return null; } 对称加密算法都可以使用Cipher类,传入算法名称、秘钥和初始向量(看分组工作模式)即可。

 

加密安全问题主要包括加密算法安全和密钥硬编码。二者均有可能造成用户信息泄露或篡改。
加密算法安全主要包括:算法安全、密钥安全、加密模式安全、IV变量安全、Hash算法安全、签名安全以及PBKDF算法安全。

 

非对称加密RSA"

   
初始化密钥
 KeyPair keyPair;
    
    public RSACryptor()
    {
        KeyPairGenerator keyPairGen;
        try
        {
            keyPairGen = KeyPairGenerator.getInstance(getAlgorithmName());
            keyPairGen.initialize(2048);
            keyPair = keyPairGen.generateKeyPair();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
加密
    public byte[] encrypt(String input)
    {
        try
        {
            PublicKey secKey = keyPair.getPublic();
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, secKey);
            return cipher.doFinal(input.getBytes());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
解密 
   public String decrypt(byte[] input)
    {
        try
        {
            PrivateKey secKey = keyPair.getPrivate();
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, secKey);
            return new String(cipher.doFinal(input));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

 

posted @ 2017-12-26 23:45  eaglediao  阅读(359)  评论(0)    收藏  举报