Table of Contents
一、编码算法
1、URL编码
2、Base64编码
二、常见的哈希算法总结
Home Java javaTutorial Java encryption and security example analysis

Java encryption and security example analysis

Apr 26, 2023 am 08:04 AM
java

    一、编码算法

    常见的编码有ASCII码、Unicode编码。

    字母A的编码是十六进制的0x41,字母B是0x42,以此类推;ASCII只能用于英文编码,最多只能有127个字符。要想对更多的文字进行编码,就需要用占用两个字节的Unicode.而中文的“中”字使用Unicode编码就是0x4e2d,使用UTF-8则需要3个字节编码。

    所以,最简单的编码是直接给每个字符指定一个若干字节表示的整数,复杂一点的编码就需要根据已有的编码推算出来。比如UTF-8编码,它是一种不定长编码,但可以从给定字符的Unicode编码推算出来。

    1、URL编码

    1.1概念

    URL编码是浏览器发送给服务器时使用的编码,它通常附加在URL的参数部分,eg

    https://www.baidu.com/s?wd=%E6%9D%A8%E9%A2%96

    之所以需要URL编码,是因为处于兼容性考虑,很多服务器只识别ASCII字符。但如果URL中包含中文,日文这些非ASCII字符怎么办?URL编码有一套规则:

    ·如果字符是A~z,a~z, 0~9以及-,_,.,*,则保持不变;

    ·如果是其他字符,先转换为UTF-8编码,然后对每个字节以%xx表示。

    例如:字符"中"的UTF-8编码是0xe4b8ad,因此,它的URL编码是%E4%B8%AD。URL编码总是大写。

    1.2代码示例(编码和解码)

    对URL中的中文进行编码

    package com.yy.demo01;
     
    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    import java.net.URLEncoder;
     
    public class Test01 {
        public static void main(String[] args) throws UnsupportedEncodingException {
            String url  = "http://www.baidu.com/s?wd=";
            String value = "杨颖";
            
            //对URL中的中文进行编码
            String result = URLEncoder.encode(value, "utf-8");
            System.out.println("URL参数:" + result);
            System.out.println("完整网址:" + (url+result));
            
            
        }
     
    }
    Copy after login

    Java encryption and security example analysis

    对URL中的中文进行解码

    package com.yy.demo01;
     
    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    import java.net.URLEncoder;
     
    public class Test01 {
        public static void main(String[] args) throws UnsupportedEncodingException {
            
            //对URL中的中文进行解码
            String param = "https://www.baidu.com/s?wd=
                         %E6%88%91%E6%9C%AC%E5%B0%86%E5%BF%83%E5%90%91%E6%98%8E%E6%9C%88\r\n";
            String conent = URLDecoder.decode(param, "utf-8");
            System.out.println(conent);
        }
     
    }
    Copy after login

    Java encryption and security example analysis

    注意:URL编码是编码算法,不是加密算法。

    URL编码目的:把任意文本数据编码为%前缀表示的文本,编码后的文本仅包含A-Z,a-z,0-9,-,_,.,*和%,便于浏览器和服务器处理。

    2、Base64编码

    2.1基本概念

    URL 编码是对字符进行编码,表示成%xx的形式,而Base64编码是对二进制数据进行编码,表示成文本格式。

    Base64编码可以把任意长度的二进制数据变为纯文本,并且纯文本内容中且只包含指定字符内容:A~2 .a~z、0~9、+、7、日。它的原理是把3字节的二进制数据按6bit一组,用4个int整数表示,然后查表,把int整数用索引对应到字符,得到的字符串。

    6位整数的范围总是e ~63,所以,能用64个字符表示:字符A~z 对应索引e~ 25,字符a~z对应索引26~5

    2.2在java中,二进制数据就是byte[ ] 数组、Java标准库提供Base64来对byte[ ]数组进行编码

    编码代码示例:使用Base64.getEncoder().encodeToString("xxxx".getBytes())方法进行编码(它返回值为一个字节数组,所以编码内容要转换为字节!)。

    Java encryption and security example analysis

    package com.yy.demo01;
     
    import java.io.UnsupportedEncodingException;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
     
    public class Test02 {
        public static void main(String[] args) throws UnsupportedEncodingException {
            String content = "红尘客栈风似刀,骤雨落宿命敲";
            String result = Base64.getEncoder().encodeToString(content.getBytes());
            System.out.println(result);
            
        }
     
    }
    Copy after login

    Java encryption and security example analysis

    解码内容

    使用Base64.getDecoder().decode(str)方法进行解码

    package com.yy.demo01;
     
    import java.io.UnsupportedEncodingException;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
     
    public class Test02 {
        public static void main(String[] args) throws UnsupportedEncodingException {
            
            String str = "57qi5bCY5a6i5qCI6aOO5Ly85YiA77yM6aqk6Zuo6JC95a6/5ZG95pWy";
            byte[] byteArray = Base64.getDecoder().decode(str);
            String line = new String(byteArray,"utf-8");
            System.out.printf("解码后:" +line);
            
        }
     
    }
    Copy after login

    Java encryption and security example analysis

    2.3、用Base64进行图片的编码和解码

    先使用Files.readAllBytes(Paths.get("图片的本地路径"))读取图片的字节数组,然后使用Base64.getEncoder().encodeToString(读取到的图片的字节数组)来进行编码,转化成字符串类型。使用Base64.getDecoder().decode(图片的字符串)解码,Files.write()写入指定路径。

    package com.yy.demo01;
     
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.Base64;
     
    public class Test03 {
        public static void main(String[] args) throws IOException {
            //读取图片(字节数组)
            byte[] imageByteArray = Files.readAllBytes(Paths.get("C:\\Users\\LENOVO\\Pictures\\Saved Pictures\\QQ图片20220505163951.jpg"));
            
            //将字节数组进行Base64编码,转换成“字符串形式”
            String imageDataStr = Base64.getEncoder().encodeToString(imageByteArray);
            System.out.println(imageDataStr);
            
            //Base64解码
            byte[] imageResultByteArray = Base64.getDecoder().decode(imageDataStr);
            Files.write(Paths.get("D:\\1\\3\\难哄.jpg"), imageResultByteArray);
        }
     
    }
    Copy after login

    Java encryption and security example analysis

    2.4、从文本文件中读取Mp3文件

    package com.yy.demo01;
     
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.Base64;
    import java.util.List;
     
    public class Test05 {
        public static void main(String[] args) throws IOException {
            //从文本文件中读取Mp3文件
            List<String> lines = Files.readAllLines(Paths.get("C:\\Users\\LENOVO\\Documents\\Tencent Files\\2452845234\\FileRecv\\mojito.txt"));
            
            StringBuilder sb = new StringBuilder();
            
            for(String ln : lines) {
                sb.append(ln);
            }
            
            //Base解码
            byte[] mp3ArrayBase = Base64.getDecoder().decode(sb.toString());
            Files.write(Paths.get("D:\\1\\3\\mojito.mp3"), mp3ArrayBase);
        }
     
    }
    Copy after login

    二、常见的哈希算法总结

    哈希算法(Hash)又称摘要算法(Digest),它的作业是:对任意一组输入数据进行计算,得到一个固定长度的输出摘要。哈希算法的目的是;为了验证原始数据是否被篡改。

    哈希算法最重要的特点就是:

    .相同的输入一定得到相同的输出

    .不同的输入大概率得到不同的输出

    Java字符串的hashCode()就是一个哈希算法输入是任意字符串,输出的是固定的4字节int整数;

    "hello".hashCode(); // 0x5e918d2
    "hello, java".hashCode(); // 0x7a9d88e8
    "hello, bob".hashCode(); // 0xa0dbae2f
    Copy after login

    哈希碰撞

    两个不同的输入得到了相同的输出:

    "AaAaAa".hashCode(); // 0x7460e8c0
    "BBAaBB".hashCode(); // 0x7460e8c0
     
    "通话".hashCode(); // 0x11ff03
    "重地".hashCode(); // 0x11ff03
    Copy after login

    常用哈希算法:MD

    Java encryption and security example analysis

    "MD5"算法加密普通字符串

    package com.yy.demo02;
     
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
     
    public class Test02 {
        public static void main(String[] args) {
            String passWord = "hckzfsd1";
            //7d18b6dc254c73427481f3083a3669
            //7d18b6dc254c734274810f30083a3669
            try {
                MessageDigest digest = MessageDigest.getInstance("MD5");
                digest.update(passWord.getBytes());
                
                byte[] resultByteArray = digest.digest();
                StringBuilder result = new StringBuilder();
                
                for(byte bite:resultByteArray) {
                    result.append(String.format("%02x", bite));
                }
                
                System.out.println(result);
                System.out.println(result.length());
                
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
     
    }
    Copy after login

    Java encryption and security example analysis

    MD5算法加密图片

    package com.yy.demo02;
     
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.Arrays;
     
    public class Test03 {
        public static void main(String[] args) {
            try {
                byte[] imageByteArray = Files.readAllBytes(Paths.get("D:\\1\\3\\周杰伦.jpg"));
                
                MessageDigest digest = MessageDigest.getInstance("MD5");
                digest.update(imageByteArray);
                
                byte[] resultByteArray = digest.digest();
                System.out.println(Arrays.toString(resultByteArray));
                System.out.println(resultByteArray.length);
                
                StringBuilder digestResult = new StringBuilder();
                for(byte b : resultByteArray) {
                    digestResult.append(String.format("%02x", b));
                }
                System.out.println(digestResult);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
     
    }
    Copy after login

    Java encryption and security example analysis

    "SHA-1"算法加密普通字符串

    package com.yy.demo02;
     
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.Arrays;
    import java.util.UUID;
     
    public class Test04 {
        public static void main(String[] args) {
            String passWord = "wbjxxmy";
            String salt = UUID.randomUUID().toString().substring(0, 5);
            System.out.println(salt);
            
            try {
                MessageDigest digest = MessageDigest.getInstance("SHA-1");
                digest.update(passWord.getBytes());
                digest.update(salt.getBytes());
                
                byte[] resultByteArray = digest.digest();
                System.out.println(Arrays.toString(resultByteArray));
                System.out.println(resultByteArray.length);
                
                StringBuilder result = new StringBuilder();
                for(byte b : resultByteArray) {
                    result.append(String.format("%02x", b));
                }
                System.out.println(result);
                
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        
     
    }
    Copy after login

    "HmacMD5"加密普通字符串

    package com.yy.demo02;
     
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.util.Arrays;
     
    import javax.crypto.KeyGenerator;
    import javax.crypto.Mac;
    import javax.crypto.SecretKey;
     
    public class Test06 {
        public static void main(String[] args) {
            String passWord = "zylsmq";
            try {
                //1.生成秘钥
                //秘钥生成器KeyGenerator
                KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
                
                //生成秘钥
                SecretKey key = keyGen.generateKey();
                
                //获取秘钥key的字节数组(64)
                byte[] keyByteArray = key.getEncoded();
                System.out.println("秘钥字节数组:" + Arrays.toString(keyByteArray));
                System.out.println("秘钥长度:" + keyByteArray.length);
                
                StringBuilder keyByteResult = new StringBuilder();
                for(byte b : keyByteArray) {
                    keyByteResult.append(String.format("%02x", b));
                }
                System.out.println(keyByteResult);
                
                
                //2.加密
                Mac mac = Mac.getInstance("HmacMD5");
                
                mac.init(key);
                
                //更新原始内容
                mac.update(passWord.getBytes());
                
                //加密
                byte[] resultByteArray = mac.doFinal();
                System.out.println("加密结果:" + resultByteArray.length + "字节");
                
                StringBuilder resultStr = new StringBuilder();
                for(byte b : resultByteArray) {
                    resultStr.append(String.format("%02x", b));
                }
                System.out.println("加密结果:" + resultStr);
                System.out.println("加密结果长度" + resultStr.length());
                
                
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
        }
     
    }
    Copy after login

    The above is the detailed content of Java encryption and security example analysis. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

    Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

    PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

    PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

    Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

    Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

    PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

    PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

    Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

    Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

    How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

    Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

    See all articles