07 Security1
07 Security1
Security
Haopeng Chen
• Contents
– Spring Security Samples
– SECURITY
• DIGITAL SIGNATURES
• CODE SIGNING
• ENCRYPTION
• Objectives
– 能够根据业务需求,配置使用合理的加密通信方式,并能够理解其基本原理与工作方式
Spring Security REliable, INtelligent & Scalable Systems
• Spring Security
– provides comprehensive support for authentication, authorization, and protection against common
exploits. It also provides integration with other libraries to simplify its usage.
– https://docs.spring.io/spring-security/site/docs/current/reference/html5/#features
3
Spring Security - Login Sample REliable, INtelligent & Scalable Systems
• MvcConfig.java
@Configuration
public class MvcConfig implements WebMvcConfigurer {
4
Login Sample REliable, INtelligent & Scalable Systems
• WebSecurityConfigureAdapter.java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
5
Spring Security - Login Sample REliable, INtelligent & Scalable Systems
• WebSecurityConfigureAdapter.java
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
6
Spring Security - Login Sample REliable, INtelligent & Scalable Systems
• home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
7
Login Sample REliable, INtelligent & Scalable Systems
• hello.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>
8
Login Sample REliable, INtelligent & Scalable Systems
• login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
9
Login Sample REliable, INtelligent & Scalable Systems
10
React + Spring Security: Front-end REliable, INtelligent & Scalable Systems
11
React + Spring Security: Front-end REliable, INtelligent & Scalable Systems
fetch(url, {
method: 'GET',
headers: headers,
credentials: 'include'
}).then(response => response.text())
.then(data => {
document.getElementById("info").innerText = data
}).catch(function (ex) {
console.log('parsing failed', ex)
})
return (
<div>
<h1 id="info">Welcome</h1>
</div>
);
}
export default Info;
12
React + Spring Security: Back-end REliable, INtelligent & Scalable Systems
• SpringSecurityApplication.java
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
}
}
• application.properties
spring.security.user.name=root
spring.security.user.password=123
13
React + Spring Security: Back-end REliable, INtelligent & Scalable Systems
• GreetingController.java
@CrossOrigin(maxAge = 3600)
@RestController
public class GreetingController {
@GetMapping("/about")
public String getAbout() {
return "This is a Spring security sample";
}
@GetMapping("/users")
public String getUser() {
return "I am a user";
}
@GetMapping("/")
public String getHome() {
return "Let' start!";
}
}
14
React + Spring Security: Back-end REliable, INtelligent & Scalable Systems
@Configuration
• SecurityConfig.java public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.authorizeRequests(authorize -> authorize
.antMatchers(“/”).permitAll()
.antMatchers(“/users”,“/about”).authenticated()
)
.httpBasic(withDefaults())
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("*"));
configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
} 15
React + Spring Security: Back-end REliable, INtelligent & Scalable Systems
• CorsConfig.java
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.exposedHeaders(HttpHeaders.SET_COOKIE)
.allowCredentials(true).maxAge(1800);
}
}
16
Run the application REliable, INtelligent & Scalable Systems
17
Digital Signatures REliable, INtelligent & Scalable Systems
18
Message Digests REliable, INtelligent & Scalable Systems
19
Message Digests REliable, INtelligent & Scalable Systems
20
Message Digests REliable, INtelligent & Scalable Systems
InputStream in = . . .
int ch;
while ((ch = in.read( )) != -1)
alg.update((byte) ch);
byte[ ] bytes = . . .;
alg.update(bytes);
21
Message Signing REliable, INtelligent & Scalable Systems
22
Message Signing REliable, INtelligent & Scalable Systems
• The keys are quite long and complex. For example, here is a matching pair of public and
private Digital Signature Algorithm (DSA) keys.
• Public key:
• Code View:
– p: fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899
bcd132acd50d99151bdc43ee737592e17 q: 962eddcc369cba8ebb260ee6b6a126d9346e38c5
g:678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e29356 30e
1c2062354d0da20a6c416e50be794ca4 y:
c0b6e67b4ac098eb1a32c5f8c4c1f0e7e6fb9d832532e27d0bdab9ca2d2a8123ce5a8018b8161a760480fadd040b927
281ddb22cb9bc4df596d7de4d1b977d50
• Private key:
• Code View:
– p: fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899
bcd132acd50d99151bdc43ee737592e17 q: 962eddcc369cba8ebb260ee6b6a126d9346e38c5 g:
678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e2935630
e1c2062354d0da20a6c416e50be794ca4 x: 146c09f881656cc6c51f27ea6c3a91b85ed1d70a
23
Message Signing REliable, INtelligent & Scalable Systems
24
X.509 Certificate REliable, INtelligent & Scalable Systems
25
X.509 Certificate REliable, INtelligent & Scalable Systems
• When generating a key, you are prompted for the following information:
Enter keystore password: password
What is your first and last name?
[Unknown]: Alice Lee
What is the name of your organizational unit?
[Unknown]: Engineering Department
What is the name of your organization?
[Unknown]: ACME Software
What is the name of your City or Locality?
[Unknown]: Cupertino
What is the name of your State or Province?
[Unknown]: California
What is the two-letter country code for this unit?
[Unknown]: US
Is <CN=Alice Lee, OU=Engineering Department, O=ACME Software, L=Cupertino, ST=California,
C=US> correct?
[no]: Y
26
X.509 Certificate REliable, INtelligent & Scalable Systems
• Once Bob trusts the certificate, he can import it into his keystore.
– keytool -importcert -keystore bob.certs -alias alice -file alice.cer
• Now Alice can start sending signed documents to Bob.
– jar cvf document.jar document.txt
– jarsigner -keystore alice.certs document.jar alice
• When Bob receives the file, he uses the -verify option of the jarsigner program.
– jarsigner -verify -keystore bob.certs document.jar
• If the JAR file is not corrupted and the signature matches, then the jarsigner program
prints
– jar verified.
– Otherwise, the program displays an error message.
28
Authentication Problem REliable, INtelligent & Scalable Systems
• Be careful:
– You still have no idea who wrote the message. Anyone could have generated a pair of public
and private keys, signed the message with the private key, and sent the signed message and
the public key to you.
– The problem of determining the identity of the sender is called the authentication problem.
29
Authentication Problem REliable, INtelligent & Scalable Systems
30
Certificate Signing REliable, INtelligent & Scalable Systems
31
Certificate Signing REliable, INtelligent & Scalable Systems
33
JAR File Signing REliable, INtelligent & Scalable Systems
• ACME decides to sign the JAR files that contain the program code.
– First, ACME generates a root certificate:
• keytool -genkeypair -keystore acmesoft.certs -alias acmeroot
– Therefore, we create a second keystore client.certs for the public certificates and add the
public acmeroot certificate into it.
• keytool -exportcert -keystore acmesoft.certs -alias acmeroot -file acmeroot.cer
• keytool -importcert -keystore client.certs -alias acmeroot -file acmeroot.cer
– To make a signed JAR file, programmers add their class files to a JAR file in the usual way. For
example,
• javac FileReadApplet.java
• jar cvf FileReadApplet.jar *.class
– Then a trusted person at ACME runs the jarsigner tool, specifying the JAR file and the alias of
the private key:
• jarsigner -keystore acmesoft.certs FileReadApplet.jar acmeroot
34
JAR File Signing REliable, INtelligent & Scalable Systems
36
Symmetric Ciphers REliable, INtelligent & Scalable Systems
• Cipher
Cipher cipher = Cipher.getInstance(algorithName);
– or
Cipher cipher = Cipher.getInstance(algorithName, providerName);
– The JDK comes with ciphers by the provider named "SunJCE".
– The algorithm name is a string such as "AES" or "DES/CBC/PKCS5Padding".
37
Symmetric Ciphers REliable, INtelligent & Scalable Systems
39
Cipher Streams REliable, INtelligent & Scalable Systems
• The JCE library provides a convenient set of stream classes that automatically encrypt
or decrypt stream data.
• Encryption
Cipher cipher = . . .;
cipher.init(Cipher.ENCRYPT_MODE, key);
CipherOutputStream out = new CipherOutputStream(new FileOutputStream(outputFileName),
cipher);
byte[] bytes = new byte[BLOCKSIZE];
int inLength = getData(bytes); // get data from data source
while (inLength != -1) {
out.write(bytes, 0, inLength);
inLength = getData(bytes); // get more data from data source
} out.flush();
40
Cipher Streams REliable, INtelligent & Scalable Systems
• The JCE library provides a convenient set of stream classes that automatically encrypt
or decrypt stream data.
• Decryption
Cipher cipher = . . .;
cipher.init(Cipher.DECRYPT_MODE, key);
CipherInputStream in = new CipherInputStream(new FileInputStream(inputFileName), cipher);
byte[] bytes = new byte[BLOCKSIZE];
int inLength = in.read(bytes);
while (inLength != -1) {
putData(bytes, inLength); // put data to destination
inLength = in.read(bytes);
}
41
Public Key Ciphers REliable, INtelligent & Scalable Systems
42
Introduction to SSL/TLS REliable, INtelligent & Scalable Systems
• Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL),
– are technologies which allow web browsers and web servers to communicate over a secured
connection.
– This means that the data being sent is encrypted by one side, transmitted, then decrypted by the
other side before processing.
– This is a two-way process, meaning that both the server AND the browser encrypt all traffic before
sending out data.
• Another important aspect of the SSL/TLS protocol is Authentication.
– This means that during your initial attempt to communicate with a web server over a secure
connection, that server will present your web browser with a set of credentials, in the form of a
"Certificate", as proof the site is who and what it claims to be.
– In certain cases, the server may also request a Certificate from your web browser, asking for proof
that you are who you claim to be.
– This is known as "Client Authentication", although in practice this is used more for business-to-
business (B2B) transactions than with individual users. Most SSL-enabled web servers do not request
Client Authentication.
43
SSL in Tomcat REliable, INtelligent & Scalable Systems
• https://blog.csdn.net/qq_42549122/article/details/90272299
44
Configuration in Tomcat REliable, INtelligent & Scalable Systems
• Create a keystore file to store the server's private key and self-signed certificate by
executing the following command:
– Windows:
– “%JAVA_HOME%\bin\keytool” -genkey -alias tomcat -keyalg RSA -keystore “C:\Tomcat\conf\key\
tomcat.keystore” -validity 365
– Unix:
– $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA -keystore ./conf/key/tomcat.keystore
-validity 365
45
Configuration in Tomcat REliable, INtelligent & Scalable Systems
• For External Tomcat -> Edit the Tomcat Configuration File ./conf/server.xml
<Connector port=“8443”
protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true"
keystoreFile="/Users/chenhaopeng/apache-tomcat-9.0.31/conf/key/tomcat.keystore"
keystorePass="changeit">
</Connector>
46
Test SSL in Tomcat REliable, INtelligent & Scalable Systems
• Spring-boot Project
@SpringBootApplication
public class DemoApplication {
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){
TomcatServletWebServerFactory tomcat=new TomcatServletWebServerFactory(){
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint=new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection=new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(connector);
return tomcat;
}
47
Test SSL in Tomcat REliable, INtelligent & Scalable Systems
• Spring-boot Project
@SpringBootApplication
public class DemoApplication {
@Bean
public Connector connector(){
Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
48
Test SSL in Tomcat REliable, INtelligent & Scalable Systems
• MsgController.java
@RestController
public class MsgController {
@Autowired
WebApplicationContext applicationContext;
@GetMapping(value = "/msg")
public String findOne( ) {
System.out.println("Sending an email message.");
return "Hello World!";
};
}
49
Test SSL in Tomcat REliable, INtelligent & Scalable Systems
• MsgController.java
@RestController
public class MsgController {
@Autowired
WebApplicationContext applicationContext;
@GetMapping(value = "/msg")
public String findOne( ) {
System.out.println("Sending an email message.");
return "Hello World!";
};
}
50
References REliable, INtelligent & Scalable Systems