Java加密与解密

Posted Storm_L

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java加密与解密相关的知识,希望对你有一定的参考价值。

Base64

Base64是网络上最常见的用于传输8Bit(1Byte)字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。Base64编码变长,具有不可读性。其实Base64是一种编码方式而不是加密方式。 

 1 public class Base64 implements Encryption, Decryption {
 2 
 3     private static Base64 instance;
 4 
 5     private Base64() {
 6     }
 7 
 8     public static synchronized Base64 getInstance() {
 9         return instance == null ? new Base64() : instance;
10     }
11 
12     @Override
13     public byte[] encrypt(byte[] src) {
14         return java.util.Base64.getEncoder().encode(src);
15     }
16 
17     @Override
18     public byte[] decrypt(byte[] src) {
19         return java.util.Base64.getDecoder().decode(src);
20     }
21 }

 

MD5

MD5即Message-Digest Algorithm 5(信息-摘要算法5),用于确保信息传输完整一致。是计算机广泛使用的杂凑算法之一(又译摘要算法、哈希算法),主流编程语言普遍已有MD5实现。将数据(如汉字)运算为另一固定长度值,是杂凑算法的基础原理。

public class Md5 implements Encryption {

    private static Md5 instance;

    private Md5() {
    }

    public static synchronized Md5 getInstance() {
        return instance == null ? new Md5() : instance;
    }

    @Override
    public byte[] encrypt(byte[] src) {
        MessageDigest md;
        byte[] result;
        try {
            md = MessageDigest.getInstance(Algorithm.MD5.value());
            md.update(src);
            result = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("No such algorithm: " + Algorithm.MD5.value());
        }
        return result;
    }
}

 

Sha1

安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准(Digital Signature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。对于长度小于2^64位的消息,SHA1会产生一个160位的消息摘要。该算法的思想是接收一段明文,然后以一种不可逆的方式将它转换成一段(通常更小)密文,散列函数值可以说是对明文的一种“指纹”或是“摘要”所以对散列值的数字签名就可以视为对此明文的数字签名。

 1 public class Sha implements Encryption {
 2 
 3     private static Sha instance;
 4 
 5     private Sha() {
 6     }
 7 
 8     public static synchronized Sha getInstance() {
 9         return instance == null ? new Sha() : instance;
10     }
11 
12     @Override
13     public byte[] encrypt(byte[] src) {
14         MessageDigest md;
15         byte[] result;
16         try {
17             md = MessageDigest.getInstance(Algorithm.SHA.value());
18             md.update(src);
19             result = md.digest();
20         } catch (NoSuchAlgorithmException e) {
21             throw new RuntimeException("No such algorithm: " + Algorithm.SHA.value());
22         }
23         return result;
24     }
25 }

 

Pbe

PBE算法(Password Based Encryption,基于口令加密)是一种基于口令的加密算法,其特点是使用口令代替了密钥,而口令由用户自己掌管,采用随机数杂凑多重加密等方法保证数据的安全性。

public class Pbe implements Encryption, Decryption {

    /**
     * define the iteration count: 1000<br>
     */
    private static final int ITERATION_COUNT = 1000;

    /**
     * define the PBE password<br>
     */
    private static final String PBE_PASSWORD = "enfldsgbnlsngdlksdsgm";

    /**
     * define the salt<br>
     */
    private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33,
            (byte) 0x10, (byte) 0x12, };

    private static Pbe instance;

    private Pbe() {
    }

    public static synchronized Pbe getInstance() {
        return instance == null ? new Pbe() : instance;
    }

    @Override
    public byte[] encrypt(byte[] src) {
        Key key = getPBEKey();
        PBEParameterSpec parameterSpec = new PBEParameterSpec(SALT, ITERATION_COUNT);
        Cipher cipher;
        byte[] result;
        try {
            cipher = Cipher.getInstance(Algorithm.PBE.value());
            cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
            result = cipher.doFinal(src);
        } catch (Exception e) {
            throw new RuntimeException("Encrypt failed.");
        }

        return result;
    }

    @Override
    public byte[] decrypt(byte[] src) {
        Key key = getPBEKey();
        PBEParameterSpec parameterSpec = new PBEParameterSpec(SALT, ITERATION_COUNT);
        Cipher cipher;
        byte[] result;
        try {
            cipher = Cipher.getInstance(Algorithm.PBE.value());
            cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
            result = cipher.doFinal(src);
        } catch (Exception e) {
            throw new RuntimeException("Decrypt failed.");
        }

        return result;
    }

    /**
     * Generate a PBE secret key according to the PBE password.<br>
     * 
     * @return
     */
    private static Key getPBEKey() {
        SecretKeyFactory keyFactory;
        SecretKey secretKey;
        try {
            keyFactory = SecretKeyFactory.getInstance(Algorithm.PBE.value());
            PBEKeySpec keySpec = new PBEKeySpec(PBE_PASSWORD.toCharArray());
            secretKey = keyFactory.generateSecret(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("No such algorithm: " + Algorithm.PBE.value());
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("The key is Invalid.");
        }

        return secretKey;
    }
}

 

Hmac

HMAC是密钥相关的哈希运算消息认证码,HMAC运算利用哈希算法,以一个密钥和一个消息为输入,生成一个消息摘要作为输出。HMAC是密钥相关的哈希运算消息认证码,HMAC运算利用哈希算法,以一个密钥和一个消息为输入,生成一个消息摘要作为输出。

 1 public class Hmac implements Encryption {
 2 
 3     private static Hmac instance;
 4 
 5     private static byte[] macKey;
 6 
 7     private Hmac() {
 8     }
 9 
10     public static synchronized Hmac getInstance() {
11         if (instance == null) {
12             macKey = initMacKey();
13             instance = new Hmac();
14         }
15 
16         return instance;
17     }
18 
19     @Override
20     public byte[] encrypt(byte[] src) {
21         SecretKey secretKey = new SecretKeySpec(macKey, Algorithm.HMAC.value());
22         Mac mac;
23         byte[] result;
24         try {
25             mac = Mac.getInstance(secretKey.getAlgorithm());
26             mac.init(secretKey);
27             result = mac.doFinal(src);
28         } catch (NoSuchAlgorithmException e) {
29             throw new RuntimeException("No such algorithm: " + secretKey.getAlgorithm());
30         } catch (InvalidKeyException e) {
31             throw new RuntimeException("The key is Invalid.");
32         }
33 
34         return result;
35     }
36 
37     /**
38      * Generate a MAC secret key.<br>
39      * 
40      * @return MAC key
41      */
42     private static byte[] initMacKey() {
43         KeyGenerator keyGenerator;
44         Key result;
45         try {
46             keyGenerator = KeyGenerator.getInstance(Algorithm.HMAC.value());
47             result = keyGenerator.generateKey();
48         } catch (NoSuchAlgorithmException e) {
49             throw new RuntimeException("No such algorithm: " + Algorithm.HMAC.value());
50         }
51         return result.getEncoded();
52     }
53 }

 

[其他代码]

 1 public enum Algorithm {
 2 
 3     BASE64("BASE64"), MD5("MD5"), SHA("SHA"), HMAC("HmacMD5"), PBE("PBEWITHMD5ANDDES");
 4 
 5     private String value;
 6 
 7     private Algorithm(String value) {
 8         this.value = value;
 9     }
10 
11     public String value() {
12         return value;
13     }
14 }
public interface Decryption {
    byte[] decrypt(byte[] src);
}
public interface Encryption {
    byte[] encrypt(byte[] src);
}

 

以上是关于Java加密与解密的主要内容,如果未能解决你的问题,请参考以下文章

php与java通用AES加密解密算法

可以解密加密数据的片段吗?

Java 课堂作业 加密与解密

Java开发经验分享之JAVA简单实现DES加密与实现DES解密

Java 加密和解密 PDF

Java 加密和解密 PDF