├── source
├── .gitignore
├── javafx-login
│ ├── src
│ │ └── main
│ │ │ ├── resources
│ │ │ ├── images
│ │ │ │ └── key.png
│ │ │ └── css
│ │ │ │ └── my.css
│ │ │ └── java
│ │ │ └── sample
│ │ │ └── LoginDialog.java
│ └── pom.xml
├── string-format
│ ├── src
│ │ └── main
│ │ │ └── java
│ │ │ └── sample
│ │ │ ├── sample2.java
│ │ │ └── sample1.java
│ └── pom.xml
├── java-keygen
│ ├── src
│ │ └── main
│ │ │ └── java
│ │ │ └── sample
│ │ │ ├── sample2.java
│ │ │ ├── sample1.java
│ │ │ ├── sample3.java
│ │ │ └── sample4.java
│ └── pom.xml
└── rsa-encryption
│ ├── pom.xml
│ └── src
│ └── main
│ └── java
│ └── sample
│ └── sample1.java
├── README.md
└── LICENSE
/source/.gitignore:
--------------------------------------------------------------------------------
1 | target
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Java Sample Source Code
2 |
3 | * Java Keygen: Illustrates RSA Key pair generation and signing and
4 | verifying data files.
5 |
6 |
--------------------------------------------------------------------------------
/source/javafx-login/src/main/resources/images/key.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaysridhar/java-stuff/HEAD/source/javafx-login/src/main/resources/images/key.png
--------------------------------------------------------------------------------
/source/javafx-login/src/main/resources/css/my.css:
--------------------------------------------------------------------------------
1 | .dialog-pane {
2 | -fx-background-color: azure;
3 | }
4 |
5 | .dialog-pane .label {
6 | -fx-text-fill: black;
7 | }
8 |
9 | .dialog-pane .content {
10 | /* -fx-background-color: white; */
11 | }
12 |
13 | .dialog-pane .header-panel .label {
14 | -fx-font-weight: bold;
15 | -fx-font-size: 3em;
16 | }
17 |
--------------------------------------------------------------------------------
/source/string-format/src/main/java/sample/sample2.java:
--------------------------------------------------------------------------------
1 | package sample;
2 |
3 | import java.math.BigInteger;
4 | import java.math.BigDecimal;
5 |
6 | import java.util.Date;
7 | import java.util.Formatter;
8 |
9 | public class sample2
10 | {
11 | static public void main(String[] args) throws Exception
12 | {
13 | StringBuilder sbuf = new StringBuilder();
14 | Formatter fmt = new Formatter(sbuf);
15 | fmt.format("PI = %f%n", Math.PI);
16 | System.out.print(sbuf.toString());
17 | sbuf.append("That's all folks.");
18 | System.out.print(sbuf.toString());
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/source/string-format/src/main/java/sample/sample1.java:
--------------------------------------------------------------------------------
1 | package sample;
2 |
3 | import java.math.BigInteger;
4 | import java.math.BigDecimal;
5 |
6 | import java.util.Date;
7 |
8 | public class sample1
9 | {
10 | static public void main(String[] args) throws Exception
11 | {
12 | if ( args.length == 0 ) {
13 | System.err.println("usage: java sample1 formatStr ..");
14 | System.exit(1);
15 | }
16 |
17 | for (int i = 0 ; i < args.length ; i++) {
18 | System.out.printf(args[i],
19 | /* 1 */'p',
20 | /* 2 */"Hello World",
21 | /* 3 */93,
22 | /* 4 */32.445,
23 | /* 5 */new BigInteger("3278904234790239"),
24 | /* 6 */new BigDecimal("348394389834535.4893483"),
25 | /* 7 */null,
26 | /* 8 */true,
27 | /* 9 */false,
28 | /* 10 */'\u00A5',
29 | /* 11 */new Date(),
30 | /* 12 */-36,
31 | /* 13 */10000000);
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Jay Sridhar
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/source/java-keygen/src/main/java/sample/sample2.java:
--------------------------------------------------------------------------------
1 | package sample;
2 |
3 | import java.io.Writer;
4 | import java.io.FileWriter;
5 | import java.io.OutputStreamWriter;
6 | import java.io.OutputStream;
7 | import java.io.FileOutputStream;
8 |
9 | import java.security.Key;
10 | import java.security.KeyPair;
11 | import java.security.KeyPairGenerator;
12 |
13 | import java.util.Base64;
14 |
15 | public class sample2
16 | {
17 | static private Base64.Encoder encoder = Base64.getEncoder();
18 |
19 | static private void writeBinary(OutputStream out,Key key)
20 | throws java.io.IOException
21 | {
22 | out.write(key.getEncoded());
23 | }
24 |
25 | static public void main(String[] args) throws Exception
26 | {
27 | if ( args.length != 3 ) {
28 | System.err.println("usage: java algo keySize outFile");
29 | System.exit(1);
30 | }
31 |
32 | int index = 0;
33 | String algo = args[index]; index++;
34 | int keySize = Integer.parseInt(args[index]); index++;
35 | String outFile = args[index]; index++;
36 |
37 | KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);
38 |
39 | /* initialize with keySize: typically 2048 for RSA */
40 | kpg.initialize(keySize);
41 | KeyPair kp = kpg.generateKeyPair();
42 |
43 | OutputStream out = null;
44 | try {
45 | System.err.println("Private key format: " +
46 | kp.getPrivate().getFormat());
47 | out = new FileOutputStream(outFile + ".key");
48 | writeBinary(out, kp.getPrivate());
49 | out.close();
50 |
51 | System.err.println("Public key format: " +
52 | kp.getPublic().getFormat());
53 | out = new FileOutputStream(outFile + ".pub");
54 | writeBinary(out, kp.getPublic());
55 | } finally {
56 | if ( out != null ) out.close();
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/source/java-keygen/pom.xml:
--------------------------------------------------------------------------------
1 |
5 | 4.0.0
6 | sample
7 | sample
8 | 0.1.0-SNAPSHOT
9 | sample
10 |
11 |
12 | UTF-8
13 | 1.17.3
14 | 1.8
15 | sample.sample1
16 |
17 |
18 |
19 |
20 |
21 |
22 | org.apache.maven.plugins
23 | maven-compiler-plugin
24 | 3.1
25 |
26 | ${javac.target}
27 | ${javac.target}
28 | ${javac.target}
29 | -Xlint
30 |
31 |
32 |
33 | maven-clean-plugin
34 | 2.5
35 |
36 |
37 |
38 | .
39 |
40 | **/*~
41 |
42 |
43 |
44 |
45 |
46 |
47 | org.codehaus.mojo
48 | exec-maven-plugin
49 | 1.5.0
50 |
51 | java
52 | -classpath %classpath ${exec.class} ${args}
53 |
54 |
55 |
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/source/string-format/pom.xml:
--------------------------------------------------------------------------------
1 |
5 | 4.0.0
6 | sample
7 | sample
8 | 0.1.0-SNAPSHOT
9 | sample
10 |
11 |
12 | UTF-8
13 | 1.17.3
14 | 1.8
15 | sample.sample1
16 |
17 |
18 |
19 |
20 |
21 |
22 | org.apache.maven.plugins
23 | maven-compiler-plugin
24 | 3.1
25 |
26 | ${javac.target}
27 | ${javac.target}
28 | ${javac.target}
29 | -Xlint
30 |
31 |
32 |
33 | maven-clean-plugin
34 | 2.5
35 |
36 |
37 |
38 | .
39 |
40 | **/*~
41 |
42 |
43 |
44 |
45 |
46 |
47 | org.codehaus.mojo
48 | exec-maven-plugin
49 | 1.5.0
50 |
51 | java
52 | -classpath %classpath ${exec.class} ${args}
53 |
54 |
55 |
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/source/java-keygen/src/main/java/sample/sample1.java:
--------------------------------------------------------------------------------
1 | package sample;
2 |
3 | import java.io.Writer;
4 | import java.io.FileWriter;
5 | import java.io.OutputStreamWriter;
6 |
7 | import java.security.Key;
8 | import java.security.KeyPair;
9 | import java.security.KeyPairGenerator;
10 |
11 | import java.util.Base64;
12 |
13 | public class sample1
14 | {
15 | static private Base64.Encoder encoder = Base64.getEncoder();
16 |
17 | static private void writeBase64(Writer out,Key key)
18 | throws java.io.IOException
19 | {
20 | byte[] buf = key.getEncoded();
21 | out.write(encoder.encodeToString(buf));
22 | out.write("\n");
23 | }
24 |
25 | static public void main(String[] args) throws Exception
26 | {
27 | if ( args.length == 0 ) {
28 | System.err.println("usage: java algo keySize [outFile]");
29 | System.exit(1);
30 | }
31 |
32 | int index = 0;
33 | String algo = args[index]; index++;
34 | int keySize = Integer.parseInt(args[index]); index++;
35 | String outFile = null;
36 | if ( index < args.length ) outFile = args[index]; index++;
37 |
38 | KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);
39 |
40 | /* initialize with keySize: typically 2048 for RSA */
41 | kpg.initialize(keySize);
42 | KeyPair kp = kpg.generateKeyPair();
43 |
44 | Writer out = null;
45 | try {
46 | if ( outFile != null ) out = new FileWriter(outFile + ".key");
47 | else out = new OutputStreamWriter(System.out);
48 |
49 | System.err.println("Private key format: " +
50 | kp.getPrivate().getFormat());
51 | out.write("-----BEGIN RSA PRIVATE KEY-----\n");
52 | writeBase64(out, kp.getPrivate());
53 | out.write("-----END RSA PRIVATE KEY-----\n");
54 |
55 | if ( outFile != null ) {
56 | out.close();
57 | out = new FileWriter(outFile + ".pub");
58 | }
59 |
60 | System.err.println("Public key format: " +
61 | kp.getPublic().getFormat());
62 | out.write("-----BEGIN RSA PUBLIC KEY-----\n");
63 | writeBase64(out, kp.getPublic());
64 | out.write("-----END RSA PUBLIC KEY-----\n");
65 | } finally {
66 | if ( out != null ) out.close();
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/source/java-keygen/src/main/java/sample/sample3.java:
--------------------------------------------------------------------------------
1 | package sample;
2 |
3 | import java.io.OutputStream;
4 | import java.io.FileOutputStream;
5 | import java.io.InputStream;
6 | import java.io.FileInputStream;
7 |
8 | import java.nio.file.Files;
9 | import java.nio.file.Paths;
10 | import java.nio.file.Path;
11 |
12 | import java.security.Key;
13 | import java.security.PrivateKey;
14 | import java.security.KeyPair;
15 | import java.security.KeyPairGenerator;
16 | import java.security.KeyFactory;
17 | import java.security.Signature;
18 |
19 | import java.security.spec.PKCS8EncodedKeySpec;
20 |
21 | import java.util.Base64;
22 |
23 | public class sample3
24 | {
25 | static private Base64.Encoder encoder = Base64.getEncoder();
26 |
27 | static private void writeBinary(OutputStream out,Key key)
28 | throws java.io.IOException
29 | {
30 | out.write(key.getEncoded());
31 | }
32 |
33 | static public void main(String[] args) throws Exception
34 | {
35 | if ( args.length != 4 ) {
36 | System.err.println("generate digital signature.");
37 | System.err.println("usage: java algo pvtKeyFile dataFile signFile");
38 | System.exit(1);
39 | }
40 |
41 | int index = 0;
42 | String algo = args[index]; index++;
43 | String keyFile = args[index]; index++;
44 | String dataFile = args[index]; index++;
45 | String signFile = args[index]; index++;
46 |
47 | /* Read the private key bytes */
48 | Path path = Paths.get(keyFile);
49 | byte[] bytes = Files.readAllBytes(path);
50 |
51 | /* Generate private key. */
52 | PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes);
53 | KeyFactory kf = KeyFactory.getInstance("RSA");
54 | PrivateKey pvt = kf.generatePrivate(ks);
55 |
56 | Signature sign = Signature.getInstance("SHA256withRSA");
57 | sign.initSign(pvt);
58 |
59 | InputStream in = null;
60 | try {
61 | in = new FileInputStream(dataFile);
62 | byte[] buf = new byte[2048];
63 | int len;
64 | while ((len = in.read(buf)) != -1) {
65 | sign.update(buf, 0, len);
66 | }
67 | } finally {
68 | if ( in != null ) in.close();
69 | }
70 |
71 | OutputStream out = null;
72 | try {
73 | out = new FileOutputStream(signFile);
74 | byte[] signature = sign.sign();
75 | out.write(signature);
76 | } finally {
77 | if ( out != null ) out.close();
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/source/java-keygen/src/main/java/sample/sample4.java:
--------------------------------------------------------------------------------
1 | package sample;
2 |
3 | import java.io.OutputStream;
4 | import java.io.FileOutputStream;
5 | import java.io.InputStream;
6 | import java.io.FileInputStream;
7 |
8 | import java.nio.file.Files;
9 | import java.nio.file.Paths;
10 | import java.nio.file.Path;
11 |
12 | import java.security.Key;
13 | import java.security.PrivateKey;
14 | import java.security.KeyPair;
15 | import java.security.KeyPairGenerator;
16 | import java.security.KeyFactory;
17 | import java.security.Signature;
18 | import java.security.PublicKey;
19 |
20 | import java.security.spec.PKCS8EncodedKeySpec;
21 | import java.security.spec.X509EncodedKeySpec;
22 |
23 | import java.util.Base64;
24 |
25 | public class sample4
26 | {
27 | static private Base64.Encoder encoder = Base64.getEncoder();
28 |
29 | static private void writeBinary(OutputStream out,Key key)
30 | throws java.io.IOException
31 | {
32 | out.write(key.getEncoded());
33 | }
34 |
35 | static public void main(String[] args) throws Exception
36 | {
37 | if ( args.length != 4 ) {
38 | System.err.println("verify digital signature.");
39 | System.err.println("usage: java algo pubKeyFile dataFile signFile");
40 | System.exit(1);
41 | }
42 |
43 | int index = 0;
44 | String algo = args[index]; index++;
45 | String keyFile = args[index]; index++;
46 | String dataFile = args[index]; index++;
47 | String signFile = args[index]; index++;
48 |
49 | /* Read the public key bytes */
50 | Path path = Paths.get(keyFile);
51 | byte[] bytes = Files.readAllBytes(path);
52 |
53 | /* Generate public key. */
54 | X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes);
55 | KeyFactory kf = KeyFactory.getInstance("RSA");
56 | PublicKey pub = kf.generatePublic(ks);
57 |
58 | Signature sign = Signature.getInstance("SHA256withRSA");
59 | sign.initVerify(pub);
60 |
61 | InputStream in = null;
62 | try {
63 | in = new FileInputStream(dataFile);
64 | byte[] buf = new byte[2048];
65 | int len;
66 | while ((len = in.read(buf)) != -1) {
67 | sign.update(buf, 0, len);
68 | }
69 | } finally {
70 | if ( in != null ) in.close();
71 | }
72 |
73 | /* Read the signature bytes */
74 | path = Paths.get(signFile);
75 | bytes = Files.readAllBytes(path);
76 | System.out.println(dataFile + ": Signature " +
77 | (sign.verify(bytes) ? "OK" : "Not OK"));
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/source/javafx-login/pom.xml:
--------------------------------------------------------------------------------
1 |
5 | 4.0.0
6 | sample
7 | sample
8 | 0.1.0-SNAPSHOT
9 | sample
10 |
11 |
12 | UTF-8
13 | 1.17.3
14 | 1.8
15 | sample.sample1
16 |
17 |
18 |
19 |
20 |
21 |
22 | org.apache.maven.plugins
23 | maven-compiler-plugin
24 | 3.1
25 |
26 | ${javac.target}
27 | ${javac.target}
28 | ${javac.target}
29 | -Xlint
30 |
31 |
32 |
33 | maven-clean-plugin
34 | 2.5
35 |
36 |
37 |
38 | .
39 |
40 | **/*~
41 |
42 |
43 |
44 |
45 |
46 |
47 | org.codehaus.mojo
48 | exec-maven-plugin
49 | 1.5.0
50 |
51 | java
52 | -classpath %classpath ${exec.class} ${args}
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 | org.openjdk.jmh
61 | jmh-core
62 | ${jmh.version}
63 |
64 |
65 | org.openjdk.jmh
66 | jmh-generator-annprocess
67 | ${jmh.version}
68 | provided
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/source/rsa-encryption/pom.xml:
--------------------------------------------------------------------------------
1 |
5 | 4.0.0
6 | sample
7 | sample
8 | 0.1.0-SNAPSHOT
9 | sample
10 |
11 |
12 | UTF-8
13 | 1.17.3
14 | 1.8
15 | sample.sample1
16 |
17 |
18 |
19 |
20 |
21 |
22 | org.apache.maven.plugins
23 | maven-compiler-plugin
24 | 3.1
25 |
26 | ${javac.target}
27 | ${javac.target}
28 | ${javac.target}
29 | -Xlint
30 |
31 |
32 |
33 | maven-clean-plugin
34 | 2.5
35 |
36 |
37 |
38 | .
39 |
40 | **/*~
41 |
42 |
43 |
44 |
45 |
46 |
47 | org.codehaus.mojo
48 | exec-maven-plugin
49 | 1.5.0
50 |
51 | java
52 | -classpath %classpath ${exec.class} ${args}
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 | org.openjdk.jmh
61 | jmh-core
62 | ${jmh.version}
63 |
64 |
65 | org.openjdk.jmh
66 | jmh-generator-annprocess
67 | ${jmh.version}
68 | provided
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/source/javafx-login/src/main/java/sample/LoginDialog.java:
--------------------------------------------------------------------------------
1 | package sample;
2 |
3 | /*
4 | * Copyright 2017 Jay Sridhar
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining
7 | * a copy of this software and associated documentation files (the
8 | * "Software"), to deal in the Software without restriction, including
9 | * without limitation the rights to use, copy, modify, merge, publish,
10 | * distribute, sublicense, and/or sell copies of the Software, and to
11 | * permit persons to whom the Software is furnished to do so, subject to
12 | * the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be
15 | * included in all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 | *
25 | * @Author Jay Sridhar
26 | */
27 |
28 | import java.util.Optional;
29 | import javafx.util.Pair;
30 | import javafx.scene.Node;
31 | import javafx.scene.control.Dialog;
32 | import javafx.scene.control.Label;
33 | import javafx.scene.control.Button;
34 | import javafx.scene.control.PasswordField;
35 | import javafx.scene.control.TextField;
36 | import javafx.scene.control.ButtonType;
37 | import javafx.scene.control.ButtonBar;
38 | import javafx.scene.control.DialogPane;
39 | import javafx.scene.layout.GridPane;
40 | import javafx.scene.layout.Priority;
41 | import javafx.scene.image.ImageView;
42 | import javafx.scene.image.Image;
43 | import javafx.geometry.Insets;
44 | import javafx.geometry.HPos;
45 | import javafx.application.Platform;
46 | import javafx.application.Application;
47 | import javafx.stage.Stage;
48 | import javafx.scene.Scene;
49 | import javafx.scene.Parent;
50 | import javafx.event.ActionEvent;
51 | import javafx.beans.value.ChangeListener;
52 |
53 | public class LoginDialog extends Application
54 | {
55 | private Parent makeContents()
56 | {
57 | DialogPane root = new DialogPane();
58 | root.setHeaderText("Enter Credentials");
59 | root.setGraphic(new ImageView(getClass().getResource("/images/key.png").toString()));
60 | root.setPadding(new Insets(10, 30, 10, 30));
61 | root.getStylesheets().add(getClass().getResource("/css/my.css").toString());
62 |
63 | ButtonType okButton = new ButtonType("Login", ButtonBar.ButtonData.OK_DONE);
64 | root.getButtonTypes().addAll(okButton, ButtonType.CANCEL);
65 | ((Button)root.lookupButton(ButtonType.CANCEL)).setOnAction(event -> Platform.exit());
66 | Button button = ((Button)root.lookupButton(okButton));
67 |
68 | GridPane grid = new GridPane();
69 | grid.setHgap(10);
70 | grid.setVgap(10);
71 | grid.setPadding(new Insets(10, 40, 10, 40));
72 |
73 | TextField username = new TextField();
74 | username.setPromptText("Username");
75 | username.setPrefWidth(300);
76 | GridPane.setHgrow(username, Priority.ALWAYS);
77 |
78 | PasswordField password = new PasswordField();
79 | password.setPromptText("Password");
80 | GridPane.setHgrow(password, Priority.ALWAYS);
81 |
82 | ChangeListener cl = (obs, ov, nv) -> {
83 | button.setDisable(username.textProperty().getValue().isEmpty() ||
84 | password.textProperty().getValue().isEmpty() );
85 | };
86 |
87 | username.textProperty().addListener(cl);
88 | password.textProperty().addListener(cl);
89 |
90 | {
91 | Node node = new Label("Username:");
92 | GridPane.setHalignment(node, HPos.RIGHT);
93 | grid.add(node, 0, 0);
94 | }
95 |
96 | grid.add(username, 1, 0);
97 |
98 | {
99 | Node node = new Label("Password:");
100 | GridPane.setHalignment(node, HPos.RIGHT);
101 | grid.add(node, 0, 1);
102 | }
103 |
104 | grid.add(password, 1, 1);
105 |
106 | root.setContent(grid);
107 |
108 | {
109 | button.setDisable(true);
110 | button.setOnAction(e -> {
111 | String uname = username.getText();
112 | String pwd = password.getText();
113 | System.out.println("Login with: " + uname + ", " + pwd);
114 | Platform.exit();
115 | });
116 | }
117 |
118 | Platform.runLater(() -> username.requestFocus());
119 |
120 | return root;
121 | }
122 |
123 | @Override
124 | public void start(Stage stage) throws Exception
125 | {
126 | Scene scene = new Scene(makeContents());
127 | stage.resizableProperty().setValue(Boolean.FALSE);
128 | stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/key.png")));
129 | stage.setTitle("Application Login");
130 | stage.setScene(scene);
131 | stage.show();
132 | }
133 |
134 | static public void main(String[] args) throws Exception
135 | {
136 | Application.launch(args);
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/source/rsa-encryption/src/main/java/sample/sample1.java:
--------------------------------------------------------------------------------
1 | package sample;
2 |
3 | import java.nio.file.Files;
4 | import java.nio.file.Paths;
5 | import java.io.FileWriter;
6 | import java.io.InputStream;
7 | import java.io.OutputStream;
8 | import java.io.FileInputStream;
9 | import java.io.FileOutputStream;
10 | import java.util.Base64;
11 | import java.util.Arrays;
12 | import java.security.Key;
13 | import java.security.KeyPair;
14 | import java.security.KeyPairGenerator;
15 | import java.security.KeyFactory;
16 | import java.security.PrivateKey;
17 | import java.security.PublicKey;
18 | import java.security.SecureRandom;
19 | import java.security.spec.PKCS8EncodedKeySpec;
20 | import java.security.spec.X509EncodedKeySpec;
21 | import javax.crypto.Cipher;
22 | import javax.crypto.KeyGenerator;
23 | import javax.crypto.SecretKey;
24 | import javax.crypto.spec.SecretKeySpec;
25 | import javax.crypto.spec.IvParameterSpec;
26 |
27 | public class sample1
28 | {
29 | static private Base64.Encoder encoder = Base64.getEncoder();
30 | static SecureRandom srandom = new SecureRandom();
31 |
32 | static private void processFile(Cipher ci,InputStream in,OutputStream out)
33 | throws javax.crypto.IllegalBlockSizeException,
34 | javax.crypto.BadPaddingException,
35 | java.io.IOException
36 | {
37 | byte[] ibuf = new byte[1024];
38 | int len;
39 | while ((len = in.read(ibuf)) != -1) {
40 | byte[] obuf = ci.update(ibuf, 0, len);
41 | if ( obuf != null ) out.write(obuf);
42 | }
43 | byte[] obuf = ci.doFinal();
44 | if ( obuf != null ) out.write(obuf);
45 | }
46 |
47 | static private void processFile(Cipher ci,String inFile,String outFile)
48 | throws javax.crypto.IllegalBlockSizeException,
49 | javax.crypto.BadPaddingException,
50 | java.io.IOException
51 | {
52 | try (FileInputStream in = new FileInputStream(inFile);
53 | FileOutputStream out = new FileOutputStream(outFile)) {
54 | processFile(ci, in, out);
55 | }
56 | }
57 |
58 | static private void doGenkey(String[] args)
59 | throws java.security.NoSuchAlgorithmException,
60 | java.io.IOException
61 | {
62 | if ( args.length == 0 ) {
63 | System.err.println("genkey -- need fileBase");
64 | return;
65 | }
66 |
67 | int index = 0;
68 | String fileBase = args[index++];
69 | KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
70 | kpg.initialize(2048);
71 | KeyPair kp = kpg.generateKeyPair();
72 | try (FileOutputStream out = new FileOutputStream(fileBase + ".key")) {
73 | out.write(kp.getPrivate().getEncoded());
74 | }
75 |
76 | try (FileOutputStream out = new FileOutputStream(fileBase + ".pub")) {
77 | out.write(kp.getPublic().getEncoded());
78 | }
79 | }
80 |
81 | /* Larger data gives:
82 | *
83 | * javax.crypto.IllegalBlockSizeException: Data must not be longer
84 | * than 245 bytes
85 | */
86 | static private void doEncrypt(String[] args)
87 | throws java.security.NoSuchAlgorithmException,
88 | java.security.spec.InvalidKeySpecException,
89 | javax.crypto.NoSuchPaddingException,
90 | javax.crypto.BadPaddingException,
91 | java.security.InvalidKeyException,
92 | javax.crypto.IllegalBlockSizeException,
93 | java.io.IOException
94 | {
95 | if ( args.length != 2 ) {
96 | System.err.println("enc pvtKeyFile inputFile");
97 | System.exit(1);
98 | }
99 |
100 | int index = 0;
101 | String pvtKeyFile = args[index++];
102 | String inputFile = args[index++];
103 | byte[] bytes = Files.readAllBytes(Paths.get(pvtKeyFile));
104 | PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes);
105 | KeyFactory kf = KeyFactory.getInstance("RSA");
106 | PrivateKey pvt = kf.generatePrivate(ks);
107 |
108 | Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
109 | cipher.init(Cipher.ENCRYPT_MODE, pvt);
110 | processFile(cipher, inputFile, inputFile + ".enc");
111 | }
112 |
113 | static private void doDecrypt(String[] args)
114 | throws java.security.NoSuchAlgorithmException,
115 | java.security.spec.InvalidKeySpecException,
116 | javax.crypto.NoSuchPaddingException,
117 | javax.crypto.BadPaddingException,
118 | java.security.InvalidKeyException,
119 | javax.crypto.IllegalBlockSizeException,
120 | java.io.IOException
121 | {
122 | if ( args.length != 2 ) {
123 | System.err.println("dec pubKeyFile inputFile");
124 | System.exit(1);
125 | }
126 |
127 | int index = 0;
128 | String pubKeyFile = args[index++];
129 | String inputFile = args[index++];
130 | byte[] bytes = Files.readAllBytes(Paths.get(pubKeyFile));
131 | X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes);
132 | KeyFactory kf = KeyFactory.getInstance("RSA");
133 | PublicKey pub = kf.generatePublic(ks);
134 |
135 | Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
136 | cipher.init(Cipher.DECRYPT_MODE, pub);
137 | processFile(cipher, inputFile, inputFile + ".ver");
138 | }
139 |
140 | static private void doEncryptRSAWithAES(String[] args)
141 | throws java.security.NoSuchAlgorithmException,
142 | java.security.InvalidAlgorithmParameterException,
143 | java.security.InvalidKeyException,
144 | java.security.spec.InvalidKeySpecException,
145 | javax.crypto.NoSuchPaddingException,
146 | javax.crypto.BadPaddingException,
147 | javax.crypto.IllegalBlockSizeException,
148 | java.io.IOException
149 | {
150 | if ( args.length != 2 ) {
151 | System.err.println("enc pvtKeyFile inputFile");
152 | System.exit(1);
153 | }
154 |
155 | int index = 0;
156 | String pvtKeyFile = args[index++];
157 | String inputFile = args[index++];
158 | byte[] bytes = Files.readAllBytes(Paths.get(pvtKeyFile));
159 | PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes);
160 | KeyFactory kf = KeyFactory.getInstance("RSA");
161 | PrivateKey pvt = kf.generatePrivate(ks);
162 |
163 | KeyGenerator kgen = KeyGenerator.getInstance("AES");
164 | kgen.init(128);
165 | SecretKey skey = kgen.generateKey();
166 |
167 | byte[] iv = new byte[128/8];
168 | srandom.nextBytes(iv);
169 | IvParameterSpec ivspec = new IvParameterSpec(iv);
170 |
171 | try (FileOutputStream out = new FileOutputStream(inputFile + ".enc")) {
172 | {
173 | Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
174 | cipher.init(Cipher.ENCRYPT_MODE, pvt);
175 | byte[] b = cipher.doFinal(skey.getEncoded());
176 | out.write(b);
177 | System.err.println("AES Key Length: " + b.length);
178 | }
179 |
180 | out.write(iv);
181 | System.err.println("IV Length: " + iv.length);
182 |
183 | Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
184 | ci.init(Cipher.ENCRYPT_MODE, skey, ivspec);
185 | try (FileInputStream in = new FileInputStream(inputFile)) {
186 | processFile(ci, in, out);
187 | }
188 | }
189 | }
190 |
191 | static private void doDecryptRSAWithAES(String[] args)
192 | throws java.security.NoSuchAlgorithmException,
193 | java.security.InvalidAlgorithmParameterException,
194 | java.security.InvalidKeyException,
195 | java.security.spec.InvalidKeySpecException,
196 | javax.crypto.NoSuchPaddingException,
197 | javax.crypto.BadPaddingException,
198 | javax.crypto.IllegalBlockSizeException,
199 | java.io.IOException
200 | {
201 | if ( args.length != 2 ) {
202 | System.err.println("enc pvtKeyFile inputFile");
203 | System.exit(1);
204 | }
205 |
206 | int index = 0;
207 | String pubKeyFile = args[index++];
208 | String inputFile = args[index++];
209 | byte[] bytes = Files.readAllBytes(Paths.get(pubKeyFile));
210 | X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes);
211 | KeyFactory kf = KeyFactory.getInstance("RSA");
212 | PublicKey pub = kf.generatePublic(ks);
213 |
214 | try (FileInputStream in = new FileInputStream(inputFile)) {
215 | SecretKeySpec skey = null;
216 | {
217 | Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
218 | cipher.init(Cipher.DECRYPT_MODE, pub);
219 | byte[] b = new byte[256];
220 | in.read(b);
221 | byte[] keyb = cipher.doFinal(b);
222 | skey = new SecretKeySpec(keyb, "AES");
223 | }
224 |
225 | byte[] iv = new byte[128/8];
226 | in.read(iv);
227 | IvParameterSpec ivspec = new IvParameterSpec(iv);
228 |
229 | Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
230 | ci.init(Cipher.DECRYPT_MODE, skey, ivspec);
231 |
232 | try (FileOutputStream out = new FileOutputStream(inputFile+".ver")){
233 | processFile(ci, in, out);
234 | }
235 | }
236 | }
237 |
238 | static public void main(String[] args) throws Exception
239 | {
240 | if ( args.length == 0 ) {
241 | System.err.print("usage: java sample1 command params..\n" +
242 | "where commands are:\n" +
243 | " genkey fileBase\n" +
244 | " tnyenc pvtKeyFile inputFile\n" +
245 | " tnydec pubKeyFile inputFile\n" +
246 | " enc pvtKeyFile inputFile\n" +
247 | " dec pubKeyFile inputFile\n");
248 | System.exit(1);
249 | }
250 |
251 | int index = 0;
252 | String command = args[index++];
253 | String[] params = Arrays.copyOfRange(args, index, args.length);
254 | if ( command.equals("genkey") ) doGenkey(params);
255 | else if ( command.equals("tnyenc") ) doEncrypt(params);
256 | else if ( command.equals("tnydec") ) doDecrypt(params);
257 | else if ( command.equals("enc") ) doEncryptRSAWithAES(params);
258 | else if ( command.equals("dec") ) doDecryptRSAWithAES(params);
259 | else throw new Exception("Unknown command: " + command);
260 | }
261 | }
262 |
--------------------------------------------------------------------------------