Java加密算法:base64,MD5加密,对称加密,非对称加密

news2025/7/28 5:02:41

目录

Java:密码算法

1、base64加密方式

2、jdk原生api实现MD5

3、使用codec依赖实现MD5加密

4、SHA加密

5、MAC算法加密

6、对称加密

7、非对称加密


Java:密码算法

1、base64加密方式

public class demo {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "张三写java";
        //编码
        String encodedStr = Base64.getEncoder().encodeToString(str.getBytes(UTF8));
        System.out.println("encodedStr:" + encodedStr);

        //解码
        byte[] decode = Base64.getDecoder().decode(encodedStr.getBytes(UTF8));
        System.out.println("decode:"+ new String(decode,UTF8));

    }
}

结果:

URL编码

public class URLTest {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "张三写java";
        //编码
        String encodedStr = URLEncoder.encode(str,UTF8);
        System.out.println("编码:"+encodedStr);
        //解码
        String decode = URLDecoder.decode(encodedStr,UTF8);
        System.out.println("解码后:"+decode);

    }
}

结果:

MD5: Message-Digest Algorithm,结果占128位==>16个byte=>转成16进制字符后是32个

11111111--->ff

2、jdk原生api实现MD5

public class MD5Test {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        String algorithm = "MD5";
        //获取消息摘要算法对象
        MessageDigest md = MessageDigest.getInstance(algorithm);
        //  获取原始内容的字节数组
        byte[] originalBytes = str.getBytes(UTF8);
        //获取到摘要结果
        byte[] digestBytes = md.digest(originalBytes);
        //当originalBytes比较大的时候,循环的进行update()
        //md.update(originalBytes);
        //md.digest();
        //把每一个字节转为16进制字符,最终再拼接起来这些16进制字符
       String hexStr = converBytes(digestBytes);
        System.out.println("hexStr:" + hexStr);
    }

    private static String converBytes(byte[] digestBytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : digestBytes) {
            //获取b的补码的后8位
            String hex = Integer.toHexString(((int)b)&0xff);
            // 15-->Integer.toHexString (15&Oxff)-->f-->0f
            // 16-- >Integer.toHexString(16&0xff)->10
            if (hex.length() == 1){
                hex = "0" + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}

 代码封装,把上面公共部分提取出来

public class HexUtils {
    
    /**
     * @description 把字节数组转为16进制字符串,如果一个字节转为16进制字符后不足两位,则前面补0
     * @author
     * @date 2023-02-23 21:02:13
     * @param digestBytes
     * @return {@link String}
     */
    public static String converBytes(byte[] digestBytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : digestBytes) {
            //获取b的补码的后8位
            String hex = Integer.toHexString(((int)b)&0xff);
            // 15-->Integer.toHexString (15&Oxff)-->f-->0f
            // 16-- >Integer.toHexString(16&0xff)->10
            if (hex.length() == 1){
                hex = "0" + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }
     /**
     * 把16进制字符串(一定是偶数位的,因为converBytes已经处理过)转为字节数组
     * @param hexStr 16进制字符串
     * @return
     */
    public static byte[] converHex2Bytes(String hexStr) {
        //一个字节可以转为2个16进制字符
        int length = hexStr.length() / 2;

        byte[] reault = new byte[length];

        for (int i = 0; i < length; i++) {
            //hexStr : abcd
            //Integer.parseInt :把s转为10进制数,radix指定s是什么进制的数
            //获取每个字节的高4位, hexStr.substring(2,3)=>c
            int high4 = Integer.parseInt(hexStr.substring(i * 2,i * 2 + 1),16);
            //获取每个字节的低4位,hexStr.substring( 3,4)=>d
            int low4 = Integer.parseInt(hexStr.substring(i * 2 + 1,i * 2 + 2),16);
            reault[i] = (byte) (high4* 16 + low4);
        }
   return reault;
}
public class MessageDigestUtils {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    /**
     * @description 执行信息再要
     * @author
     * @date 2023-02-23 21:09:55
     * @param originContent 原始字符串
     * @param algorithm 算法名字,如MD5
     * @return {@link String}
     */
    public static String doDigest(String originContent,String algorithm){

        try {
            //获取消息摘要算法对象
            MessageDigest md = MessageDigest.getInstance(algorithm);
            //  获取原始内容的字节数组
            byte[] originalBytes = originContent.getBytes(UTF8);
            //获取到摘要结果
            byte[] digestBytes = md.digest(originalBytes);
            //当originalBytes比较大的时候,循环的进行update()
            //md.update(originalBytes);
            //md.digest();
            //把每一个字节转为16进制字符,最终再拼接起来这些16进制字符
            String hexStr = HexUtils.converBytes(digestBytes);
            return hexStr;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

3、使用codec依赖实现MD5加密

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.15</version>
        </dependency>
public class MD5Test {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        System.out.println( "str:" + DigestUtils.md5Hex(str.getBytes(UTF8)));
    }
}

结果: 

4、SHA加密

SHA(Secure Hash Algorithm) :安全散列算法

sha-256=>转成16进制字符后是64个

其他如sha-0,sha-1, sha-512

SHA-256加密:

public class Sha256Test {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        String algorithm = "SHA-256";
        //封装的类进行编码
        String hexStr = MessageDigestUtils.doDigest(str,algorithm);
        System.out.println("自己封装的str:" + hexStr);

        System.out.println("codec的str:" + DigestUtils.sha256Hex(str.getBytes(UTF8)));
    }
}

结果:

SHA-512

public class SHA512Test {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        String algorithm = "SHA-512";
        //封装的类进行编码
        String hexStr = MessageDigestUtils.doDigest(str,algorithm);
        System.out.println("自己封装的str:" + hexStr);

        System.out.println("codec的str:" + DigestUtils.sha512Hex(str.getBytes(UTF8)));
    }
}

5、MAC算法加密

MAC(Message Authentication Code):消息认证码,是一种带有秘钥的hash函数

使用jdk实现在添加一个方法 

/**
     * @description 获取mac的消息摘要
     * @author
     * @date 2023-02-23 21:37:36
     * @param originContent 原始内容
     * @param algorithm mac算法的key
     * @param key 算法名字,例如HmacMD5
     * @return {@link String}
     */
    public static String doMacDigest(String originContent,String algorithm,String key){

        try {
            //获取消息摘要算法对象
            Mac mac = Mac.getInstance(algorithm);
            //
            SecretKey secretKey = new SecretKeySpec(key.getBytes(UTF8),algorithm);
            mac.init(secretKey);
            //  获取原始内容的字节数组
            byte[] originalBytes = originContent.getBytes(UTF8);
            //获取到摘要结果
            byte[] digestBytes = mac.doFinal(originalBytes);
            //当originalBytes比较大的时候,循环的进行update()
            //md.update(originalBytes);
            //md.digest();
            //把每一个字节转为16进制字符,最终再拼接起来这些16进制字符
            String hexStr = HexUtils.converBytes(digestBytes);
            return hexStr;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

使用自己封装的方法及使用codec实现mac加密

public class MACTest {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        String algorithm1 = "HmacMD5";
        String algorithm2 = "HmacSHA256";
        String algorithm3 = "HmacSHA512";
        //指定秘钥, mac摘要和digest算法( md5 , sha)不同的地方就是加了盐
        String key = "123";
        //封装的类进行编码
        String hexStr1 = MessageDigestUtils.doMacDigest(str,algorithm1,key);
        String hexStr2 = MessageDigestUtils.doMacDigest(str,algorithm2,key);
        String hexStr3 = MessageDigestUtils.doMacDigest(str,algorithm3,key);
        System.out.println("HmacMD5:" + hexStr1);
        System.out.println("HmacMD5:" + hexStr2);
        System.out.println("HmacMD5:" + hexStr3);

        String hmacMD5HexStr = new HmacUtils(HmacAlgorithms.HMAC_MD5,key.getBytes(UTF8)).hmacHex(str.getBytes(UTF8));
        String hmacSHA256HexStr = new HmacUtils(HmacAlgorithms.HMAC_SHA_256,key.getBytes(UTF8)).hmacHex(str.getBytes(UTF8));
        String hmacSHA512HexStr = new HmacUtils(HmacAlgorithms.HMAC_SHA_512,key.getBytes(UTF8)).hmacHex(str.getBytes(UTF8));
        System.out.println("hmacMD5HexStr:"+ hmacMD5HexStr);
        System.out.println("hmacSHA256HexStr:"+ hmacSHA256HexStr);
        System.out.println("hmacSHA512HexStr:"+ hmacSHA512HexStr);
    }
}

结果: 

6、对称加密

也叫单秘钥加密。所谓单秘钥,指的是加密和解密的过程使用相同的密钥,相比非对称加密,因只有一把钥匙,因而速度更快,更适合加解密大文件。

DES : data encryption standard,已经过时

AES : advanced encryption standard,替代des。
 

DES:使用Base64加密

public class DesTest {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    private static final String KEY = "12345678";
    //加密模式
    private static final String ALGORITHM = "DES";

    /**
     * 加密
     * @param text 加密内容
     * @return
     */
    public static String encrypt(String text) throws Exception {
        //获取示例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //创建加密规则
        SecretKey secretKey = new SecretKeySpec(KEY.getBytes(UTF8), ALGORITHM);
        //加密模式规则
        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
        byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
        //1,使用Base64 2,转成16进制
        return Base64.encodeBase64String(bytes);
    }

    /**
     *  解密
     * @param encodedText 加密后的字符串
     * @return
     * @throws Exception
     */
    public static String decrypt(String encodedText) throws Exception {
        //获取示例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //创建加密规则
        SecretKey secretKey = new SecretKeySpec(KEY.getBytes(UTF8), ALGORITHM);
        //加密模式规则
        cipher.init(Cipher.DECRYPT_MODE,secretKey);
        byte[] bytes = cipher.doFinal(Base64.decodeBase64(encodedText.getBytes(UTF8)));
        //1,使用Base64
        return new String(bytes,UTF8);
    }

    public static void main(String[] args) throws Exception {
         String str = "张三写java";
        //加密
        String encodedText = encrypt(str);
        System.out.println("base64编码加密后的结果"+encodedText);
        //解密
        String decrypt = decrypt(encodedText);
        System.out.println("des解密后的结果"+decrypt);
    }
}

结果:

 AES:16进制加密模式

public class AesTest {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    //aes默认key的长度 16,24,32位
    private static final String KEY = "12345678abcdefgh";
    //加密模式
    private static final String ALGORITHM = "AES";

    /**
     * 加密
     * @param text 加密内容
     * @return
     */
    public static String encrypt(String text) throws Exception {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, KEY);
        byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
        //转成16进制
        return HexUtils.converBytes(bytes);
    }

    /**
     *  解密
     * @param encodedText 16进制编码后的字符串
     * @return
     * @throws Exception
     */
    public static String decrypt(String encodedText) throws Exception {
        byte[] bytes = HexUtils.converHex2Bytes(encodedText);
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE, KEY);
        byte[] decryptedBytes = cipher.doFinal(bytes);
        //2,转成16进制
        return new String(decryptedBytes,UTF8);
    }

    /**
     * 获取Cipher对象
     * @param type 加密解密模式
     * @param seed 密钥
     * @return
     * @throws Exception
     */
    public static Cipher getCipher(int type,String seed) throws Exception{
        //获取示例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //创建加密规则
        SecretKey secretKey = new SecretKeySpec(seed.getBytes(UTF8), ALGORITHM);
        //加密模式规则
        cipher.init(type,secretKey);

        return cipher;
    }

    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        //加密
        String encodedText = encrypt(str);
        System.out.println("16进制编码aes加密后的结果"+encodedText);
        //解密
        String decrypt = decrypt(encodedText);
        System.out.println("aes解密后的结果"+decrypt);
    }
}

 

AES:16进制加密模式代码优化

public class AesTest {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    //aes默认key的长度 16,24,32位
    private static final String KEY = "12345678";
    //加密模式
    private static final String ALGORITHM = "AES";

    /**
     * 加密
     * @param text 加密内容
     * @return
     */
    public static String encrypt(String text) throws Exception {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, KEY);
        byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
        //转成16进制
        return HexUtils.converBytes(bytes);
    }

    /**
     *  解密
     * @param encodedText 16进制编码后的字符串
     * @return
     * @throws Exception
     */
    public static String decrypt(String encodedText) throws Exception {
        byte[] bytes = HexUtils.converHex2Bytes(encodedText);
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE, KEY);
        byte[] decryptedBytes = cipher.doFinal(bytes);
        //2,转成16进制
        return new String(decryptedBytes,UTF8);
    }

    /**
     * 获取Cipher对象
     * @param type 加密解密模式
     * @param seed 密钥
     * @return
     * @throws Exception
     */
    public static Cipher getCipher(int type,String seed) throws Exception{
        //获取示例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //创建加密规则
        //创建keyGenerator对象,可以根据传入的key生成一个指定长度的key
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        //初始化secureRandom,并指定生成指定长度key的算法
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(seed.getBytes(UTF8));
        keyGenerator.init(128,secureRandom);
        //通过keyGenerator生成新的秘钥
        SecretKey secretKey = keyGenerator.generateKey();
        //获取到新秘钥的字节数组
        byte[] encoded = secretKey.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(encoded, ALGORITHM);

        //加密模式规则
        cipher.init(type,secretKeySpec);

        return cipher;
    }

    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        //加密
        String encodedText = encrypt(str);
        System.out.println("16进制编码aes加密后的结果"+encodedText);
        //解密
        String decrypt = decrypt(encodedText);
        System.out.println("aes解密后的结果"+decrypt);
    }
}

AES:base64加密模式 

public class AesBase64Test {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    private static final String KEY = "12345678";
    //加密模式
    private static final String ALGORITHM = "AES";

    /**
     * 加密
     * @param text 加密内容
     * @return
     */
    public static String encrypt(String text) throws Exception {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, KEY);
        byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
        //1,使用Base64 2,转成16进制
        return Base64.encodeBase64String(bytes);
    }

    /**
     *  解密
     * @param encodedText 加密后的字符串
     * @return
     * @throws Exception
     */
    public static String decrypt(String encodedText) throws Exception {
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE, KEY);
        byte[] bytes = cipher.doFinal(Base64.decodeBase64(encodedText.getBytes(UTF8)));
        //1,使用Base64 2,转成16进制
        return new String(bytes,UTF8);
    }

    public static Cipher getCipher(int type,String seed) throws Exception{
        //获取示例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //创建加密规则
        //创建keyGenerator对象,可以根据传入的key生成一个指定长度的key
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        //初始化secureRandom,并指定生成指定长度key的算法
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(seed.getBytes(UTF8));
        keyGenerator.init(128,secureRandom);
        //通过keyGenerator生成新的秘钥
        SecretKey secretKey = keyGenerator.generateKey();
        //获取到新秘钥的字节数组
        byte[] encoded = secretKey.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(encoded, ALGORITHM);

        //加密模式规则
        cipher.init(type,secretKeySpec);

        return cipher;
    }

    /**
     * 测试
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        //加密
        String encodedText = encrypt(str);
        System.out.println("base64编码aes加密后的结果" + encodedText);
        //解密
        String decrypt = decrypt(encodedText);
        System.out.println("aes解密后的结果" + decrypt);
    }
}

 

7、非对称加密

定义:加密和解密使用的是两个不同的密钥(public key和private key).公钥可以给任何人,私钥总

是自己保留。

常见算法:RSA

应用场景:

1、加解密:可以使用公钥加密,对应的就是私钥解密;也可以使用私钥加密,对应的就是公钥解

密。

public class RSATest2 {
    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";

    //生成密钥对,一般来说执行一次就行
    public static Map<String, String> createKeys(int keySize) {
        //为RSA算法创建一个KeyPairGenerator对象(KeyPairGenerator,密钥对生成器,用于生成公钥和私钥对)
        KeyPairGenerator kpg;
        try {
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }

        //初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        //生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        //得到公钥
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded()); //返回一个publicKey经过二次加密后的字符串
        //得到私钥
        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded()); //返回一个privateKey经过二次加密后的字符串

        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);

        return keyPairMap;
    }

    /**
     * 得到公钥
     *
     * @param publicKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws Exception {
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 得到私钥
     *
     * @param privateKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception {
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥加密
     *
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 公钥解密
     *
     * @param data
     * @param publicKey
     * @return
     */

    public static String publicDecrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
        int maxBlock = 0;
        if (opmode == Cipher.DECRYPT_MODE) {
            maxBlock = keySize / 8;
        } else {
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try {
            while (datas.length > offSet) {
                if (datas.length - offSet > maxBlock) {
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        } catch (Exception e) {
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    }



    //测试
    public static void main(String[] args) throws Exception {
        //生成公私钥
        Map<String, String> keyMap = RSATest2.createKeys(512);
        //公钥
        String publicKey = keyMap.get("publicKey");
        
        //私钥
        String privateKey = keyMap.get("privateKey");


        System.out.println("公钥加密——私钥解密");
        String str = "法外狂徒张三";
        System.out.println("明文:" + str);
        System.out.println("明文大小:" + str.getBytes().length);
        //对内容进行公钥加密
        String encodedData = RSATest2.publicEncrypt(str, RSATest2.getPublicKey(publicKey));
        System.out.println("公钥加密密文:" + encodedData);
        //用私钥对密文进行解密

        String decodedData = RSATest2.privateDecrypt(encodedData, RSATest2.getPrivateKey(privateKey));
        System.out.println("解密后文字: " + decodedData);
    }

}

2、数字签名

3、数字信封

4、数字证书

参考视频:密码学-java信息安全,摘要算法,对称加密(AES)/非对称加密(RSA),一应俱全_哔哩哔哩_bilibili

非对称加密参考:java实现非对称加密(RSA)_qq_1473179505的博客-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/368053.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

搜索引擎的6个技巧

今天看了一期seo优化的视频&#xff0c;其中就有这么一篇关于百度搜索的几个小技巧&#xff0c;这里整理出来&#xff0c;分享给大家。不是标题党&#xff0c;真的99%的人都不知道这个6个小技巧。 搜索引擎一般都会有一些高级的搜索技巧&#xff0c;掌握这些技巧之后就可以过滤…

spring的启动过程(二) :springMvc的启动过程

在上一篇文章中&#xff0c;我们详解了spring的启动过程&#xff0c;这一篇介绍spring mvc的启动过程&#xff0c;那么spring和spring mvc有什么联系呢。 1.Spring和SpringMVC是父子容器关系。2.Spring整体框架的核心思想是容器&#xff0c;用来管理bean的生命周期&#xff0c;…

CAN总线开发一本全(3) - 微控制器集成的FlexCAN外设

CAN总线开发一本全&#xff08;3&#xff09; - 微控制器集成的FlexCAN外设 苏勇&#xff0c;2023年2月 文章目录CAN总线开发一本全&#xff08;3&#xff09; - 微控制器集成的FlexCAN外设引言硬件外设模块系统概要总线接口单元 - 寄存器清单数据结构 - 消息缓冲区MB初始化过…

taobao.top.oaid.merge( OAID订单合并 )

&#xffe5;开放平台免费API必须用户授权 基于OAID&#xff08;收件人ID&#xff0c; Open Addressee ID)做订单合并&#xff0c;确保相同收件人信息的订单合并到相同组。 公共参数 请求地址: HTTP地址 http://gw.api.taobao.com/router/rest 公共请求参数: 公共响应参数: 请…

win10环境下安装java开发环境安装java

一&#xff1a;环境介绍 安装系统版本&#xff1a;win10 java版本&#xff1a;java SE 17 二&#xff1a;下载Java安装包 官网下载Java安装包&#xff1a;Java Downloads | Oracle 中国 选择需要的Java版本进行下载&#xff0c;如果没有要选择的版本&#xff0c;可以选择最新…

称重传感器差分输入信号隔离转换直流放大变送器0-±10mV/0-±20mV转0-10V/4-20mA

主要特性DIN11 IPO 压力应变桥信号处理系列隔离放大器是一种将差分输入信号隔离放大、转换成按比例输出的直流信号导轨安装变送模块。产品广泛应用在电力、远程监控、仪器仪表、医疗设备、工业自控等行业。此系列模块内部嵌入了一个高效微功率的电源&#xff0c;向输入端和输出…

(二十九)大白话MySQL直接强行把redo log写入磁盘?

上一讲我们给大家说了一下redo log block这个概念&#xff0c;大家现在都知道平时我们执行完增删改之后&#xff0c;要写入磁盘的redo log&#xff0c;其实应该是先进入到redo log block这个数据结构里去的&#xff0c;然后再进入到磁盘文件里&#xff0c;如下图所示。 那么今天…

三、锁相关知识

文章目录锁的分类可重入锁、不可重入锁乐观锁、悲观锁公平锁、非公平锁互斥锁、共享锁深入synchronized类锁、对象锁synchronized的优化synchronized实现原理synchronized的锁升级重量锁底层ObjectMonitor深入ReentrantLockReentrantLock和synchronized的区别AQS概述加锁流程源…

Flink中遇到的问题

目录 1、提交flink 批处理任务时遇到的问题 2、flink定时任务&#xff0c;mysql连接超时问题 3、yarn 增加并行任务数量配置 4、flink checkpoint 恢复失败 5、flink程序在hadoop集群跑了一段时间莫名挂掉 1、提交flink 批处理任务时遇到的问题 问题描述&#xff1a; …

超详细树状数组讲解(+例题:动态求连续区间和)

树状数组的作用&#xff1a;快速的对数列的一段范围求和快速的修改数列的某一个数为什么要使用树状数组&#xff1a;大家从作用中看到快速求和的时候可能会想到为什么不使用前缀和只需要预处理一下就可以在O(1)的时间复杂度下实行对于数列的一段范围的和但是我们可以得到当我们…

记一次服务器入侵事件的应急响应

0x01 事件背景 8月某日&#xff0c;客户官网被黑&#xff0c;需在特定时间内完成整改。为避免客户业务受到影响&#xff0c;实验室相关人员第一时间展开本次攻击事件的应急处理。 0x02 事件分析 网站源码被篡改&#xff0c;攻击者一定获取到了权限&#xff0c;那么接下来的思…

Linux进程1 - 进程的相关概念

目录 1.进程的概念 2.并行和并发 3.PCB&#xff08;进程控制块&#xff09; 4.进程状态 1.进程的概念 程序&#xff1a;二进制文件&#xff0c;占用的磁盘空间进程&#xff1a;启动的程序所有的数据都在内存中需要占用更多的系统资源cpu,物理内存 2.并行和并发 并发----在…

Spring事物和事务的传播机制

事务的定义&#xff1a;将一组操作封装到一个执行单元&#xff0c;要么全部成功&#xff0c;要么全部失败。 一、Spring中事务的实现 Spring中事务的操作分为两类&#xff1a; 1.编程式事务&#xff08;手动写代码操作事务&#xff09; 2.声明式事务&#xff08;利用注解自动…

2023财年Q4业绩继续下滑,ChatGPT能驱动英伟达重回巅峰吗?

近年来&#xff0c;全球科创风口不断变换&#xff0c;虚拟货币、元宇宙等轮番登场&#xff0c;不少企业匆忙上台又很快谢幕&#xff0c;但在此期间&#xff0c;有些企业扮演淘金潮中“卖水人”的角色&#xff0c;却也能够见证历史且屹立不倒。不过&#xff0c;这并不意味着其可…

CSS 美化网页元素【快速掌握知识点】

目录 一、为什么使用CSS 二、字体样式 三、文本样式 color属性 四、排版文本段落 五、文本修饰和垂直对齐 1、文本装饰 2、垂直对齐方式 六、文本阴影 七、超链接伪类 1、语法 2、示例 3、访问时&#xff0c;蓝色&#xff1b;访问后&#xff0c;紫色&#xff1b; …

详解八大排序算法

文章目录前言排序算法插入排序直接插入排序:希尔排序(缩小增量排序)选择排序直接选择排序堆排序交换排序冒泡排序快速排序hoare版本挖坑法前后指针版本快速排序的非递归快速排序总结归并排序归并排序的非递归实现&#xff1a;计数排序排序算法复杂度及稳定性分析总结前言 本篇…

复杂场景的接口测试

测试场景一&#xff1a;被测业务操作是由多个API调用协作完成 背景&#xff1a;一个单一的前端操作可能会触发后端一系列的API调用&#xff0c;此时API的测试用例就不再是简单的单个API调用&#xff0c;而是一系列API的调用 存在的情况&#xff1a;存在后一个API需要使用前一个…

一文带你彻底搞懂Nginx反向代理

一文带你彻底搞懂Nginx反向代理一、什么是反向代理1.1 正向代理1.2 反向代理1.3 总结二、配置反向代理2.1 准备 Tomcat2.2 配置 Nginx一、什么是反向代理 1.1 正向代理 举一个通俗的例子&#xff0c;因为众所周知的原因&#xff0c;我们无法访问谷歌&#xff0c;但是因为某些…

Android:实现签名功能——signature-pad库

文章目录实现效果步骤1、添加 signature-pad 库的依赖。2、在 layout 文件中使用 SignaturePad 控件&#xff0c;另外添加“清空”和“保存”两个按钮。3、实现清空 SignaturePad 控件内容的功能4、实现保存 SignaturePad 控件内容的功能5、实现兼容Android10以下和Android10以…

同城创业有哪些优势可利用?本地外卖平台的行业优势可以利用

伴随着外卖市场的下沉&#xff0c;低线城市的用户开始大量使用外卖跑腿平台&#xff01; 由于中国在线外卖行业逐渐成熟&#xff0c;一二线主流市场逐渐饱和&#xff0c;外卖行业逐渐向低线城市发展。2023年&#xff0c;三线及以下城市使用外卖平台的频率几乎等于一二线城市&a…