博客
关于我
常用Java密码技术
阅读量:498 次
发布时间:2019-03-07

本文共 12209 字,大约阅读时间需要 40 分钟。

Java密码技术全面解析

1. 单向散列函数

单向散列函数,又称杂凑函数,用于将任意长度的输入消息串变换为固定长度的输出串,且输出难以反推输入。常用于消息摘要、密钥加密等场景。

1.1 MD5

MD5由RSA数据安全公司开发,是一种广泛使用的单向散列算法。尽管MD5的抗碰撞性已被破解,但其在特定场景下仍具有重要价值。

package com.huangzi.demo;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class MD5 {    public static byte[] encrypt(String info) throws NoSuchAlgorithmException {        MessageDigest md5 = MessageDigest.getInstance("MD5");        byte[] srcBytes = info.getBytes();        md5.update(srcBytes);        return md5.digest();    }    public static void main(String[] args) throws NoSuchAlgorithmException {        String msg = "皇子——常用Java密码技术";        byte[] resultBytes = MD5.encrypt(msg);        System.out.println("密文:" + new String(resultBytes));        System.out.println("明文:" + msg);    }}

1.2 SHA

SHA家族包括SHA-1、SHA-224、SHA-256、SHA-384等多种算法,SHA-1已被破解。

package com.huangzi.demo;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class SHA {    public static byte[] encrypt(String shaType, String info) throws NoSuchAlgorithmException {        MessageDigest md = MessageDigest.getInstance(shaType);        byte[] srcBytes = info.getBytes();        md.update(srcBytes);        return md.digest();    }    public static void main(String[] args) throws NoSuchAlgorithmException {        String msg = "皇子讲Java密码技术";        String[] shaTypes = { "SHA1", "SHA-256", "SHA-384", "SHA-512" };        for (String type : shaTypes) {            System.out.println(type);            byte[] resultBytes = SHA.encrypt(type, msg);            System.out.println("明文:" + msg);            System.out.println("密文:" + new String(resultBytes));            System.out.println("========================");        }    }}

2. 对称加密

对称加密使用相同的密钥进行加密和解密。

2.1 DES

DES(Data Encryption Standard)是美国联邦政府指定的块加密算法,已被废弃。

import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;public class DES {    private KeyGenerator keygen;    private SecretKey desKey;    private Cipher cipher;    private byte[] cipherByte;    public DES() throws NoSuchAlgorithmException, NoSuchPaddingException {        keygen = KeyGenerator.getInstance("DES");        desKey = keygen.generateKey();        cipher = Cipher.getInstance("DES");    }    public byte[] encrypt(String str) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {        cipher.init(Cipher.ENCRYPT_MODE, desKey);        byte[] src = str.getBytes();        cipherByte = cipher.doFinal(src);        return cipherByte;    }    public byte[] decrypt(byte[] buff) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {        cipher.init(Cipher.DECRYPT_MODE, desKey);        cipherByte = cipher.doFinal(buff);        return cipherByte;    }    public static void main(String[] args) throws Exception {        DES des = new DES();        String msg = "皇子讲Java密码技术";        byte[] enContent = des.encrypt(msg);        byte[] deContent = des.decrypt(enContent);        System.out.println("明文:" + msg);        System.out.println("密文:" + new String(enContent));        System.out.println("解密:" + new String(deContent));    }}

2.2 3DES

3DES通过三次加密提高了安全性。

package com.huangzi.demo;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;public class DES3 {    private KeyGenerator keygen;    private SecretKey des3Key;    private Cipher cipher;    private byte[] cipherByte;    public DES3() throws NoSuchAlgorithmException, NoSuchPaddingException {        keygen = KeyGenerator.getInstance("DESede");        des3Key = keygen.generateKey();        cipher = Cipher.getInstance("DESede");    }    public byte[] encrypt(String str) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {        cipher.init(Cipher.ENCRYPT_MODE, des3Key);        byte[] src = str.getBytes();        cipherByte = cipher.doFinal(src);        return cipherByte;    }    public byte[] decrypt(byte[] buff) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {        cipher.init(Cipher.DECRYPT_MODE, des3Key);        cipherByte = cipher.doFinal(buff);        return cipherByte;    }    public static void main(String[] args) throws Exception {        DES3 des3 = new DES3();        String msg = "皇子讲Java密码技术";        byte[] enContent = des3.encrypt(msg);        byte[] deContent = des3.decrypt(enContent);        System.out.println("明文:" + msg);        System.out.println("密文:" + new String(enContent));        System.out.println("解密:" + new String(deContent));    }}

2.3 AES

AES(Advanced Encryption Standard)是现代最流行的对称加密算法。

package com.huangzi.demo;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;public class AES {    private KeyGenerator keygen;    private SecretKey aesKey;    private Cipher cipher;    private byte[] cipherByte;    public AES() throws NoSuchAlgorithmException, NoSuchPaddingException {        keygen = KeyGenerator.getInstance("AES");        aesKey = keygen.generateKey();        cipher = Cipher.getInstance("AES");    }    public byte[] encrypt(String str) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {        cipher.init(Cipher.ENCRYPT_MODE, aesKey);        byte[] src = str.getBytes();        cipherByte = cipher.doFinal(src);        return cipherByte;    }    public byte[] decrypt(byte[] buff) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {        cipher.init(Cipher.DECRYPT_MODE, aesKey);        cipherByte = cipher.doFinal(buff);        return cipherByte;    }    public static void main(String[] args) throws Exception {        AES aes = new AES();        String msg = "皇子讲Java密码技术";        byte[] enContent = aes.encrypt(msg);        byte[] deContent = aes.decrypt(enContent);        System.out.println("明文:" + msg);        System.out.println("密文:" + new String(enContent));        System.out.println("解密:" + new String(deContent));    }}

2.4 PBE

PBE(Password Based Encryption)基于口令加密,使用口令生成加密密钥。

package com.huangzi.demo;import java.security.InvalidAlgorithmParameterException;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.security.spec.InvalidKeySpecException;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.PBEKeySpec;import javax.crypto.spec.PBEParameterSpec;public class PBE {    private static Cipher cipher;    private static SecretKey key;    private static PBEParameterSpec paramSpec;    public static byte[] encode(String src) throws IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException {        SecureRandom random = new SecureRandom();        byte[] salt = random.generateSeed(8);        String password = "abc123";        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBEWITHMD5andDES");        key = skf.generateSecret(keySpec);        paramSpec = new PBEParameterSpec(salt, 100);        cipher = Cipher.getInstance("PBEWITHMD5andDES");        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);        return cipher.doFinal(src.getBytes());    }    public static byte[] decode(byte[] src) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {        cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);        return cipher.doFinal(src);    }    public static void main(String[] args) throws Exception {        String msg = "皇子讲Java密码技术";        byte[] enContent = PBE.encode(msg);        byte[] deContent = PBE.decode(enContent);        System.out.println("明文:" + msg);        System.out.println("密文:" + new String(enContent));        System.out.println("解密:" + new String(deContent));    }}

3. 公钥密码

公钥密码(Public-Key Cryptography)通过使用公开的加密密钥和保留的私密解密密钥实现安全通信。

3.1 RSA

RSA是最具影响力的公钥加密算法,由Ron Rivest、Adi Shamir和Leonard Adleman提出。

package com.huangzi.demo;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.RSAPrivateKey;import java.security.RSAPublicKey;import javax.crypto.Cipher;public class RSA {    public static byte[] encrypt(RSAPublicKey publicKey, byte[] srcBytes) throws Exception {        Cipher cipher = Cipher.getInstance("RSA");        cipher.init(Cipher.ENCRYPT_MODE, publicKey);        return cipher.doFinal(srcBytes);    }    public static byte[] decrypt(RSAPrivateKey privateKey, byte[] srcBytes) throws Exception {        Cipher cipher = Cipher.getInstance("RSA");        cipher.init(Cipher.DECRYPT_MODE, privateKey);        return cipher.doFinal(srcBytes);    }    public static void main(String[] args) throws Exception {        String msg = "皇子讲Java密码技术";        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");        keyPairGen.initialize(1024);        KeyPair keyPair = keyPairGen.generateKeyPair();        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();        byte[] srcBytes = msg.getBytes();        byte[] encryptedBytes = RSA.encrypt(publicKey, srcBytes);        byte[] decryptedBytes = RSA.decrypt(privateKey, encryptedBytes);        System.out.println("明文:" + msg);        System.out.println("密文:" + new String(encryptedBytes));        System.out.println("解密结果:" + new String(decryptedBytes));    }}

3.2 数字签名

数字签名通过公钥加密实现信息验证,常用于身份验证和数据完整性验证。

package com.huangzi.demo;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.PrivateKey;import java.security.PublicKey;import java.security.Signature;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.PKCS8EncodedKeySpec;public class RSASign {    public static byte[] sign(PrivateKey privateKey, String msg) throws Exception {        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());        KeyFactory keyFactory = KeyFactory.getInstance("RSA");        PrivateKey generatedPrivateKey = keyFactory.generatePrivate(pkcs8KeySpec);        Signature signature = Signature.getInstance("MD5withRSA");        signature.initSign(generatedPrivateKey);        signature.update(msg.getBytes());        return signature.sign();    }    public static boolean verify(PublicKey publicKey, String msg, byte[] signatureBytes) throws Exception {        Signature signature = Signature.getInstance("MD5withRSA");        signature.initVerify(publicKey);        signature.update(msg.getBytes());        return signature.verify(signatureBytes);    }    public static void main(String[] args) throws Exception {        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");        keyPairGen.initialize(1024);        KeyPair keyPair = keyPairGen.generateKeyPair();        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();        String msg = "皇子讲Java密码技术";        byte[] signatureBytes = RSASign.sign(privateKey, msg);        System.out.println("消息明文:" + msg);        System.out.println("数字签名:" + new String(signatureBytes));        boolean verified = RSASign.verify(publicKey, msg, signatureBytes);        System.out.println("验签结果:" + verified);    }}

转载地址:http://nuvcz.baihongyu.com/

你可能感兴趣的文章
Objective-C实现mandelbrot曼德勃罗特集算法(附完整源码)
查看>>
Objective-C实现markov chain马尔可夫链算法(附完整源码)
查看>>
Objective-C实现MATLAB中Filter函数功能(附完整源码)
查看>>
Objective-C实现matrix chainorder矩阵链顺序算法(附完整源码)
查看>>
Objective-C实现matrix exponentiation矩阵求幂算法(附完整源码)
查看>>
Objective-C实现MatrixMultiplication矩阵乘法算法 (附完整源码)
查看>>
Objective-C实现max non adjacent sum最大非相邻和算法(附完整源码)
查看>>
Objective-C实现max subarray sum最大子数组和算法(附完整源码)
查看>>
Objective-C实现max sum sliding window最大和滑动窗口算法(附完整源码)
查看>>
Objective-C实现MaxHeap最大堆算法(附完整源码)
查看>>
Objective-C实现MaximumSubarray最大子阵列(Brute Force蛮力解决方案)算法(附完整源码)
查看>>
Objective-C实现MaximumSubarray最大子阵列(动态规划解决方案)算法(附完整源码)
查看>>
Objective-C实现maxpooling计算(附完整源码)
查看>>
Objective-C实现max_difference_pair最大差异对算法(附完整源码)
查看>>
Objective-C实现max_heap最大堆算法(附完整源码)
查看>>
Objective-C实现MD5 (附完整源码)
查看>>
Objective-C实现md5算法(附完整源码)
查看>>
Objective-C实现MeanSquareError均方误差算法 (附完整源码)
查看>>
Objective-C实现median filter中值滤波器算法(附完整源码)
查看>>
Objective-C实现memcmp函数功能(附完整源码)
查看>>