The first one, DES encryption and decryption
import java.security.Key; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * DES是一種對稱加密算法,所謂對稱加密算法:加密和解密使用相同的秘鑰的算法 * @author llp * */ public class DESUtil { private static final Logger logger = LoggerFactory.getLogger(DESUtil.class); private static Key key; //設(shè)置秘鑰key private static String KEY_STR="myKey"; private static String CHARSETNAME="UTF-8"; private static String ALGORITHM="DES"; static{ try{ //生成DES算法對象 KeyGenerator generator=KeyGenerator.getInstance(ALGORITHM); //運用SHA1安全策略 SecureRandom secureRandom=SecureRandom.getInstance("SHA1PRNG"); //設(shè)置上密鑰種子 secureRandom.setSeed(KEY_STR.getBytes()); //初始化基于SHA1的算法對象 generator.init(secureRandom); //生成密鑰對象 key=generator.generateKey(); generator=null; }catch(Exception e){ throw new RuntimeException(e); } } /** * 獲取加密的信息 * @param str * @return */ public static String getEncryptString(String str){ //基于BASE64編碼,接收byte[]并轉(zhuǎn)換成String BASE64Encoder base64Encoder=new BASE64Encoder(); try { // 按UTF8編碼 byte[] bytes = str.getBytes(CHARSETNAME); // 獲取加密對象 Cipher cipher = Cipher.getInstance(ALGORITHM); // 初始化密碼信息 cipher.init(Cipher.ENCRYPT_MODE, key); // 加密 byte[] doFinal = cipher.doFinal(bytes); // byte[]to encode好的String并返回 return base64Encoder.encode(doFinal); } catch (Exception e) { throw new RuntimeException(e); } } /** * 獲取解密之后的信息 * * @param str * @return */ public static String getDecryptString(String str) { // 基于BASE64編碼,接收byte[]并轉(zhuǎn)換成String BASE64Decoder base64decoder = new BASE64Decoder(); try { // 將字符串decode成byte[] byte[] bytes = base64decoder.decodeBuffer(str); // 獲取解密對象 Cipher cipher = Cipher.getInstance(ALGORITHM); // 初始化解密信息 cipher.init(Cipher.DECRYPT_MODE, key); // 解密 byte[] doFinal = cipher.doFinal(bytes); // 返回解密之后的信息 return new String(doFinal, CHARSETNAME); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) { //加密 logger.info(getEncryptString("root"));//WnplV/ietfQ= logger.info(getEncryptString("123456"));//QAHlVoUc49w= //解密 logger.info(getDecryptString(getEncryptString("root")));//root logger.info(getDecryptString(getEncryptString("123456")));//123456 } }
The second one, MD5 encryption
import java.security.MessageDigest; /** * MD5加密 * @author llp * */ public class MD5 { /** * 對傳入的String進行MD5加密 * * @param s * @return */ public static final String getMd5(String s) { // 16進制數(shù)組 char hexDigits[] = { '5', '0', '5', '6', '2', '9', '6', '2', '5', 'q', 'b', 'l', 'e', 's', 's', 'y' }; try { char str[]; // 將傳入的字符串轉(zhuǎn)換成byte數(shù)組 byte strTemp[] = s.getBytes(); // 獲取MD5加密對象 MessageDigest mdTemp = MessageDigest.getInstance("MD5"); // 傳入需要加密的目標數(shù)組 mdTemp.update(strTemp); // 獲取加密后的數(shù)組 byte md[] = mdTemp.digest(); int j = md.length; str = new char[j * 2]; int k = 0; // 將數(shù)組做位移 for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } // 轉(zhuǎn)換成String并返回 return new String(str); } catch (Exception e) { return null; } } public static void main(String[] args) { System.out.println(MD5.getMd5("123456"));//s05bse6q2qlb9qblls96s592y55y556s } }
PHP Chinese website has a large number of free JAVA introductory tutorials, everyone is welcome to learn!
The above is the detailed content of How to encrypt in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.
