Tech Info

Backend

SpringBoot implements data encryption and desensitization (annotation + reflection + AOP)

Scenario: In response to government requirements, commercial software should ensure that users' basic information is not "leaked" and cannot "directly display" sensitive user information such as phone numbers, ID cards, addresses, etc. According to the above scenario description, we can analyze two points: "Not leaked" means that user information should be encrypted and stored. "Cannot directly display" means that user information should be desensitized when displayed. Solution Foolish programming: Encrypt the fields related to user information entities in the project, such as name, mobile phone number, ID number, address, etc., before adding them to the database; Decrypt and desensitize the data in the database when displaying the user information list, and then return it to the frontend. Aspect-oriented programming: Mark the fields related to user information entities in the project (here we use UserBO to indicate, add @EncryptField to the name, phone fields in UserBO) with annotations, return the user information entity class (here we use UserDO to indicate, add @DecryptField to the name, phone fields in UserDO); then use @EncryptField and @DecryptField as entry points to implement encryption and decryption desensitization in an aspect-oriented way. Foolish programming does not mean foolish, it is like aspect-oriented programming. Foolish programming requires encrypting and decrypting desensitization logic processing for all interfaces related to user information, where the changes are relatively large, high risk, repetitive operations on the same logic, high workload, and difficult to maintain later; Aspect-oriented programming only needs to add annotations to user information fields, and uniformly perform encryption and decryption desensitization logic processing on fields with annotations, which is…

2023-10-25 0comments 487hotness 0likes jimmychen Read all
Android

Used Compose to make a few more loading animations, did you like it?

Through the previous article, we have initially learned how to use Compose to make loading animations. To consolidate this knowledge, in this article we will continue to use Compose to make a few more loading animations and deepen the impression. The article is relatively long and you can choose the animations you are interested in to read. Arcs and Circles I don't know what to call this animation, so I just named it randomly. The whole animation process is still quite simple. It consists of two parts: one part is two arcs revolving around the center at speeds from fast to slow, and the other part is a hollow circle in the center whose radius is oscillating between lengthening and shortening in a loop. So basically two cyclic animations can complete it. First we need to define the variables needed for the animation: centerX and centerY are the coordinates of the center of the animation, radius is the radius for drawing the two arcs. Then we create a cyclic animation with values from 0 degrees to 360 degrees: Here we use FastOutSlowInEasing for the speed variation to make the arcs rotate from fast to slow. Next we draw the two arcs in Canvas: Just draw two fan shapes, and add the angleDiff change value to startAngle. The two arcs can rotate. The effect is as follows: Next is the expanding and contracting hollow circle in the middle, which is also a cyclic process. We create another cyclic animation with the range oscillating between 20f and 60f: circleSize is the radius…

2023-10-15 0comments 596hotness 0likes jimmychen Read all
Android

Using Compose to make amazing loading animations

Spinning dots I've seen elsewhere online where someone used CSS to create an effect with several dots spinning around the center, each dot sequentially changing in size and transparency. Since CSS can do this, can we create a similar effect using Compose? Let's give it a try. First, since the dots spin around the center, we need to determine the coordinates of the center point and the radius. In the code, centerX and centerY are the coordinates of the center point, radius is the radius of the circle, and mSize gets the canvas size to dynamically update the center point coordinates and radius. We also need a set of angles - these angles will be used to draw the dots around the circumference. angleList stores the angles for drawing each dot. With these angles, we can use the sine and cosine formulas to calculate the center point coordinates for each dot: pointX and pointY are the functions to calculate the center point coordinates for each dot. Using this, we can first draw a circle of dots around the circumference. Now that we've drawn the dots, how do we make them spin and change size and transparency? We can think of this process as continuously changing the size and transparency of each dot as it is drawn. So we can create two more arrays to store the changing radius and transparency values. When drawing each dot, we can use an animation loop to pull values for each dot from the radius and alphaList arrays. This will create the change in size…

2023-10-14 0comments 446hotness 0likes jimmychen Read all
Android

Incremental Build Product DexMerge for Android app

Preface For Android applications, especially large applications, build time is a headache. Build times of several minutes or even tens of minutes are intolerable for most developers. What we face most in actual development is local incremental compilation. Although the official has done some processing on incremental compilation, the actual effect is not ideal, especially in specific projects, particularly medium and large projects. Background Currently NetEase Cloud Music and its subordinate look live broadcast, xinyu, mus and other app have successively adopted the aar of public modules, using the latest agp version and other measures, but the overall build time is still long, incremental build is generally 2-5 min. Since I am currently mainly responsible for the development of mus business, I have done some optimization work on incremental builds based on the current build situation of mus. Time Consuming Investigation Combining with the specific situation of mus construction, the main focus of the current build time consumption is concentrated in some Transform and dexMerge (agp version 4.2.1). For Transform, the main consumption is from some tools like privacy scanning, automated buried points and so on, usually the build time of these Transform has reached several minutes incrementally. In addition, the dexMeger task is also a big head during incremental builds. The incremental dexMerge build time for mus is about 35-40s, and the incremental build dexMerge time for NetEase Cloud Music is about 90-100s. Optimization Direction For large projects, basically the most time-consuming is Transform. These Transform generally fall into the following two categories: Functional Transform, removing only affects its…

2023-10-13 0comments 460hotness 0likes jimmychen Read all
Backend

Brings you to understand the usage of springboot3 + jwt + security

Preface Spring Security has become the first choice for permission verification in Java backends. Today I will take you through Security in depth by reading the code based on the open source project spring-boot-3-jwt-security. This article mainly explains Spring Security + JWT (Json Web Token) to implement user authentication and permission verification. All code is built on jdk17+. Let's get started! Technology Introduction Springboot 3.0 Spring Security Json Web Token (JWT) BCrypt Maven Project Construction The project uses postgresql database to store user information and Token (why not Redis? Leave this hole for now), you can replace it with mysql database as you like Accessing the database uses jpa, which is quite convenient for some simple sql that can be automatically mapped based on method names. It doesn't matter if you haven't used it before. It won't affect reading today's article, and can be replaced with mybatis-plus etc later according to your actual needs This article uses Lombok to generate fixed template code <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.0.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.alibou</groupId> <artifactId>security</artifactId> <version>0.0.1-SNAPSHOT</version> <name>security</name> <description>Demo project for Spring Boot</description> <properties> <java.version>17</java.version> </properties> <dependencies> <!-- jpa --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- spring security security framework --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- web dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- database --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- JWT --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.5</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.5</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.5</version> </dependency> <!-- doc remove this if not needed --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.1.0</version> </dependency>…

2023-10-07 0comments 1176hotness 0likes jimmychen Read all
Backend

WebSocket Authentication and Authorization in Spring

I. Things to Know The security chain and security configuration of HTTP and WebSocket are completely independent. SpringAuthenticationProvider is not involved in WebSocket authentication at all. In the examples given, authentication will not occur on the HTTP negotiation endpoint, because the JavaScript STOMP (websocket) libraries do not send the necessary authentication headers along with the HTTP request. Once set on the CONNECT request, the user (simpUser) will be stored in the websocket session, and subsequent messages will no longer need authentication. II. Dependencies <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-messaging</artifactId> </dependency> III. WebSocket Configuration 3.1, Simple Message Broker @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(final MessageBrokerRegistry config) { config.enableSimpleBroker("/queue/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(final StompEndpointRegistry registry) { registry.addEndpoint("stomp"); setAllowedOrigins("*") } } 3.2, Spring Security Configuration Since the Stomp protocol relies on the first HTTP request, authorization for the stomp handshake endpoint HTTP call is required. @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception http.httpBasic().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests().antMatchers("/stomp").permitAll() .anyRequest().denyAll(); } } Then create a service responsible for verifying user identity. @Component public class WebSocketAuthenticatorService { public UsernamePasswordAuthenticationToken getAuthenticatedOrFail(final String username, final String password) throws AuthenticationException { if (username == null || username.trim().isEmpty()) { throw new AuthenticationCredentialsNotFoundException("Username was null or empty."); } if (password == null || password.trim().isEmpty()) { throw new AuthenticationCredentialsNotFoundException("Password was null or empty."); } if (fetchUserFromDb(username, password) == null) { throw new BadCredentialsException("Bad credentials for user " + username); } return new UsernamePasswordAuthenticationToken( username, null, Collections.singleton((GrantedAuthority) () -> "USER")…

2023-10-06 0comments 520hotness 0likes jimmychen Read all
Security

Implement 2FA Mechanism Based on TOTP Algorithm Using Python and Golang

Since March this year (2023), Github has started to force users to enable two-step verification 2FA (two-factor) login verification, undoubtedly for security reasons, after all, once a Github account is stolen, all code repositories will be destroyed. For the necessity of two-factor login, please refer to: Don\'t let your server (vps) become a botnet (ssh brute force crack), key verification and two-way factor login are worth having. In simple terms, two-factor login is a measure to prove "you are yourself" through a third-party device. Github officially recommends downloading 1Password, Authy, Microsoft Authenticator and other APPs on the mobile side to verify by scanning the code. In fact, it is not so troublesome. This time we will implement two-factor login verification through Python/Golang code. TOTP algorithm Time-based One-Time Password (TOTP) is a time-based one-time password algorithm used to enhance identity authentication security. TOTP is based on the HMAC (Hash-based Message Authentication Code) algorithm and timestamp to generate one-time passwords. The user and server share a secret key, usually exchanged during initial authentication. Based on this key, the server generates an initial value for verification. At each time step (usually 30 seconds), based on the current timestamp and shared secret key, an HMAC algorithm is used to generate a hash value. Then, a dynamic password of fixed length is extracted from the hash value. This dynamic password is valid within the set time step, after which it will automatically expire. When authenticating, the user needs to enter the dynamic password generated within the current time step. The server will use the same…

2023-10-05 0comments 762hotness 0likes jimmychen Read all
Backend

Use Cases of Spring Security

1. Background When doing the general permission system, I used spring-security to control the permission system, and now I will summarize the most basic usage 2. Demo usage 2.1 Some basic concepts Spring Security's security management has two important concepts, Authentication and Authorization Spring Security login authentication mainly involves two important interfaces: UserDetailService and UserDetails. The UserDetailService interface mainly defines a method loadUserByUsername(String username) to complete the query of user information. username is the login name when logging in. When logging in and authenticating, you need to customize an implementation class to implement the UserDetailService interface and complete the database query. This interface returns UserDetail. The loadUserByUsername user returns UserDetails. Our own User implements UserDetails UserDetail is mainly used to encapsulate user information after successful authentication, that is, the user information returned by UserDetailService can use Spring's own User object, but it is best to implement the UserDetail interface and customize the user object What is returned after successful authentication token The token is a string generated by the server as a token for the client to request. After the first login, the server generates a token and returns this token to the client. In the future, the client only needs to bring this token to request data without having to bring the username and password again Basic dependencies <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> 2.2 Spring Security authentication steps Customize the UserDetails class: When the entity object fields do not meet the requirements, you need to customize UserDetails, generally you need to customize UserDetails Customize the UserDetailsService class, mainly used to…

2023-10-02 0comments 393hotness 0likes jimmychen Read all
Archives
  • October 2023
  • September 2023
Categories
  • Algorithm
  • Android
  • Backend
  • Embedded
  • Security
Ads

COPYRIGHT © 2023 Tech Info. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang