Java

Programming language, platform and process level virtualization .

System Properties

https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html https://docs.oracle.com/javame/config/cdc/cdc-opt-impl/ojmeec/1.0/runtime/html/localization.htm

Key

Meaning

file.separator

Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.

java.class.path

Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.

java.home

Installation directory for Java Runtime Environment (JRE)

java.vendor

JRE vendor name

java.vendor.url

JRE vendor URL

java.version

JRE version number

line.separator

Sequence used by operating system to separate lines in text files

os.arch

Operating system architecture

os.name

Operating system name

os.version

Operating system version

path.separator

Path separator character used in java.class.path

user.dir

User working directory

user.home

User home directory

user.name

User account name

user.language

Two-letter language name code based on ISO 639

user.region

Two-letter region name code based on ISO 3166

file.encoding

Default character-encoding name based on the IANA Charset MIB

Regular expressions

   1 /*
   2 javac TesteRe.java 
   3 java -cp . TesteRe 
   4 */
   5 /*
   6 gcj -C TesteRe.java  # compile with gcj, GNU compiler for Java
   7 gij -cp . TesteRe # run with gij, GNU interpreter for Java
   8 
   9 Linux executable
  10 gcj --main=TesteRe -g -o TesteRe TesteRe.java
  11 ldd TesteRe
  12 ./TesteRe
  13 */
  14 
  15 import java.util.regex.Pattern;
  16 import java.util.regex.Matcher;
  17 
  18 public class TesteRe{
  19 
  20     public static void main(String args[]){ 
  21         String values[]={"aa12.txt","a123sss.txt","bs11bb.txt","123aaaa.sql","a12.txt","aaaa12","20ghj","6657"};
  22         Pattern a = Pattern.compile("^(\\D+)(\\d+)(\\D+)$");
  23         Pattern b = Pattern.compile("^(\\d+)(\\D+)$");
  24         Pattern c = Pattern.compile("^(\\D+)(\\d+)$");
  25         Pattern d = Pattern.compile("^(\\d+)$");
  26 
  27         for(String item:values){
  28             Matcher ma = a.matcher(item);
  29             Matcher mb = b.matcher(item);
  30             Matcher mc = c.matcher(item);
  31             Matcher md = d.matcher(item);
  32 
  33            if(ma.matches()){ 
  34                int val = Integer.parseInt(ma.group(2)) + 1;
  35                System.out.println(String.format("A: mv %s %s%d%s",item,ma.group(1),val,ma.group(3)  ) );
  36            }
  37 
  38            if(mb.matches()){ 
  39                int val = Integer.parseInt(mb.group(1)) + 1;
  40                System.out.println(String.format("B: mv %s %d%s",item, val , mb.group(2)  ) );
  41            }
  42 
  43            if(mc.matches()){ 
  44                int val = Integer.parseInt(mc.group(2)) + 1;
  45                System.out.println(String.format("C: mv %s %s%d",item,mc.group(1),val   ) );
  46            }
  47 
  48            if(md.matches()){ 
  49                int val = Integer.parseInt(md.group(1)) + 1;
  50                System.out.println(String.format("D: mv %s %d",item, val  ) );
  51            }
  52 
  53         }
  54     }
  55 }

Server/client

Server

   1 import java.net.ServerSocket;
   2 import java.net.Socket;
   3 import java.lang.Thread;
   4 import java.util.Stack;
   5 
   6 public class SocketServer{
   7     public static void main(String []args){
   8         ServerSocket ss = null; 
   9         int nrThreads= Runtime.getRuntime().availableProcessors() * 2; 
  10         System.out.println("Nr cores:" + nrThreads);
  11         ConnHandler[] c = new ConnHandler[nrThreads];
  12         for(int i=0;i<nrThreads;i++){
  13             c[i]=new ConnHandler();
  14             c[i].start();
  15         }
  16         
  17         try{ 
  18             ss = new ServerSocket(1234); 
  19             ss.setReuseAddress(true);
  20         }
  21         catch(Exception ex){    }
  22         long count=0;
  23         while(true){
  24           try{
  25             Socket s = ss.accept(); 
  26             s.setSoLinger(true,0);
  27             int idx = (int)count%nrThreads;
  28             c[ idx  ].addSocket(s);
  29             count++;
  30             
  31           }
  32           catch(Exception ex){
  33               System.out.println(ex.getMessage());
  34           }
  35         }
  36     }
  37 }

ConnHandler

   1 import java.net.ServerSocket;
   2 import java.net.Socket;
   3 import java.lang.Thread;
   4 import java.util.Stack;
   5 
   6 public class ConnHandler extends Thread{
   7     private byte[] rx;
   8     private Stack stack;
   9     long tid;
  10 
  11     public ConnHandler(){
  12         this.rx= new byte[1024];
  13         this.stack = new Stack();
  14     }
  15 
  16     public void addSocket(Socket s){
  17         this.stack.push(s);
  18     }
  19 
  20     public void run(){
  21         this.tid = Thread.currentThread().getId();
  22 
  23         while(true){
  24             if( this.stack.empty() == false){
  25                 Socket s = (Socket)this.stack.pop();
  26                 try{
  27                     if( s.getInputStream().available() > 0 ){
  28                         int readedBytes = s.getInputStream().read( rx );
  29                          System.out.println("ThreadId:"+tid  + " ReadedBytes:"+ readedBytes + 
  30 " StackSize:" + this.stack.size() );
  31                     }
  32                     s.close();
  33                 }
  34                 catch(Exception ex){
  35                 } 
  36             }
  37             else{ try{ Thread.sleep(500); }catch(Exception ex){} }
  38         }
  39     }
  40 }

Client (python)

   1 import threading
   2 import time
   3 import socket
   4 
   5 class Client (threading.Thread):
   6     def __init__(self):
   7         threading.Thread.__init__(self) #required
   8 
   9     def run(self):
  10         for x in range(1,100):
  11             HOST = 'localhost'
  12             PORT = 1234
  13             s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  14             print('connecting...')
  15             s.connect((HOST, PORT))
  16             print('sending config...')
  17             s.send('test\r\n')
  18             s.close()
  19             print('complete')
  20 
  21 if __name__=='__main__':
  22     clients=[]
  23     for x in range(1,100):
  24         clients.append( Client() )
  25     for c in clients:
  26         c.start()

JAVA_TOOL_OPTIONS

Since the command-line cannot always be accessed or modified, for example in embedded VMs or simply VMs launched deep within scripts, a JAVA_TOOL_OPTIONS variable is provided so that agents may be launched in these cases.

   1 set JAVA_TOOL_OPTIONS=-Dfile.encoding=utf8
   2 export JAVA_TOOL_OPTIONS=-Dfile.encoding=utf8

http://docs.oracle.com/javase/7/docs/platform/jvmti/jvmti.html#tooloptions

Access private field via reflection

   1 java.lang.reflect.Method  m[] = ClassX.class.getDeclaredMethods();
   2 // Object invoke(Object obj, Object... args)
   3 // Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.
   4 java.lang.reflect.Field f = ClassX.class.getDeclaredField("fieldx");
   5 f.setAccessible(true);
   6 //  get(Object obj)
   7 // Returns the value of the field represented by this 
   8 // Field, on the specified object.
   9 f.get(objClassx);
  10 // set(Object obj, Object value)
  11 // Sets the field represented by this Field object 
  12 // on the specified object argument to the specified new value.
  13 f.set(objClassx, fieldValue);
  14 FieldType ft = f.get(objectWithPrivateField);

Generate Javadoc using command line

   1 dir /s /b *.java > javafiles.txt
   2 javadoc -encoding UTF-8 -d docs @javafiles.txt

To add an overview file add -overview overview.html

Java keystore public private keys

   1 keytool -genkey -alias test1rsa -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore1.p12 -validity 3650
   2 #Enter keystore password:  
   3 #Re-enter new password: 
   4 #What is your first and last name?
   5 #  [Unknown]:  
   6 #What is the name of your organizational unit?
   7 #  [Unknown]:  
   8 #What is the name of your organization?
   9 #  [Unknown]:  
  10 #What is the name of your City or Locality?
  11 #  [Unknown]:  
  12 #What is the name of your State or Province?
  13 #  [Unknown]:  
  14 #What is the two-letter country code for this unit?
  15 #  [Unknown]:  
  16 #Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
  17 #  [no]:  yes
  18 keytool -list -v -keystore keystore1.p12 -storetype pkcs12  

   1 /*
   2 javac keypair.java
   3 java -classpath . keypair
   4 */
   5 import java.security.KeyStore;
   6 import java.security.PrivateKey;
   7 import java.security.PublicKey;
   8 import java.security.Key;
   9 import java.security.cert.Certificate;
  10 import javax.crypto.Cipher;
  11 import javax.crypto.CipherOutputStream;
  12 import java.io.ByteArrayOutputStream;
  13 import java.io.FileOutputStream;
  14 import java.security.spec.X509EncodedKeySpec;
  15 import java.security.spec.PKCS8EncodedKeySpec;
  16 import java.security.spec.EncodedKeySpec;
  17 import java.io.FileInputStream;
  18 import java.security.KeyFactory;
  19 
  20 public class keypair{
  21     public static final String X509 = "X.509";
  22     public static final String RSA = "RSA";
  23     public static final String PKCS8 = "PKCS#8"; 
  24     public static final String PKCS12 = "PKCS12";
  25     
  26     private static Key loadKey(String filename,String format,String algorithm){
  27         Key ret=null;
  28         
  29         try{
  30             FileInputStream keyfis = new FileInputStream( filename );
  31             byte[] data = new byte[keyfis.available()];
  32             keyfis.read(data);
  33             keyfis.close();
  34             
  35             EncodedKeySpec spec = null;
  36             KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
  37             if(PKCS8.equals(format)){
  38                 spec = new PKCS8EncodedKeySpec(data);
  39                 ret = keyFactory.generatePrivate(spec);
  40                 System.out.println(String.format("Loading %s in format %s",filename , ret.getFormat() ) );
  41             }
  42             
  43             if(X509.equals(format)){
  44                 spec = new X509EncodedKeySpec(data);
  45                 ret = keyFactory.generatePublic(spec);
  46                 System.out.println(String.format("Loading %s in format %s",filename , ret.getFormat() ) );
  47             }            
  48         }
  49         catch(Exception ex){
  50             ex.printStackTrace();
  51         }
  52         
  53         return ret;
  54     }   
  55     
  56     private static void saveKey(Key key,String filename){
  57         try{
  58             System.out.println(String.format("Saving %s in format %s",filename , key.getFormat() ) );
  59             byte[] encodedKey = key.getEncoded();
  60             FileOutputStream keyfos = new FileOutputStream( filename );
  61             keyfos.write(encodedKey);
  62             keyfos.close();            
  63         }
  64         catch(Exception ex){
  65             ex.printStackTrace();
  66         }
  67     }
  68     
  69     private static byte[] encrypt(Key key,String payload){
  70         byte[] res=null;
  71         try{        
  72             Cipher cipher = Cipher.getInstance(key.getAlgorithm());
  73             cipher.init(Cipher.ENCRYPT_MODE, key);
  74             ByteArrayOutputStream baos = new ByteArrayOutputStream();
  75             CipherOutputStream cos = new CipherOutputStream(baos, cipher);
  76             byte[] b = payload.getBytes();
  77             System.out.println( b.length );
  78             cos.write(b);
  79             cos.flush();
  80             cos.close();            
  81             res = baos.toByteArray();
  82             
  83             System.out.println("Res size: "+ res.length );            
  84             for(int i=0;i<res.length;i++){
  85                 System.out.print(String.format("%02X",res[i]));
  86             }
  87             
  88             System.out.println();            
  89         }
  90         catch(Exception ex){
  91             ex.printStackTrace();
  92         }   
  93         return res;
  94     }
  95     
  96     private static void decrypt(Key key,byte[] res){
  97         try{        
  98             Cipher cipherDec = Cipher.getInstance(key.getAlgorithm());
  99             cipherDec.init(Cipher.DECRYPT_MODE, key);
 100             ByteArrayOutputStream baosdec = new ByteArrayOutputStream();
 101             CipherOutputStream cosdec = new CipherOutputStream(baosdec, cipherDec);
 102             System.out.println( res.length );
 103             cosdec.write(res);
 104             cosdec.flush();
 105             cosdec.close();            
 106             byte[] resDec = baosdec.toByteArray();        
 107             
 108             System.out.println("Res size: "+ resDec.length );            
 109             for(int i=0;i<resDec.length;i++){
 110                 System.out.print(String.format("%s",(char)resDec[i]));
 111             }
 112             
 113             System.out.println();
 114             
 115         }
 116         catch(Exception ex){
 117             ex.printStackTrace();
 118         }
 119     }
 120     
 121     public static void main(String args[]){
 122         KeyStore ks = null;
 123         java.io.FileInputStream fis = null;
 124         String pass = "12345678";
 125         String alias = "test1rsa";
 126         
 127         try {
 128             ks = KeyStore.getInstance(PKCS12);
 129             fis = new java.io.FileInputStream("keystore1.p12");
 130             ks.load(fis, pass.toCharArray());
 131             fis.close();
 132             KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(pass.toCharArray());         
 133             KeyStore.Entry pkEntry = ks.getEntry(alias, protParam);
 134             KeyStore.PrivateKeyEntry prvKeyEntry = ((KeyStore.PrivateKeyEntry)pkEntry);
 135             PrivateKey privateKey = prvKeyEntry.getPrivateKey();
 136             Certificate myCert = ks.getCertificate(alias);
 137             //Certificate myCert =prvKeyEntry.getCertificate();
 138             PublicKey publicKey = myCert.getPublicKey();
 139             
 140             System.out.println("PrivKeyAlg:" + privateKey.getAlgorithm() );
 141             System.out.println("PubKeyAlg:" + publicKey.getAlgorithm() );
 142             //------------------
 143 
 144             byte[] res = encrypt(privateKey,"secret");
 145             decrypt(publicKey,res);            
 146             
 147             byte[] resOther = encrypt(publicKey,"otherSecret");
 148             decrypt(privateKey,resOther);            
 149             saveKey(publicKey,"publicKey.bin");
 150             saveKey(privateKey,"privateKey.bin");
 151             
 152             loadKey("publicKey.bin", X509,RSA);
 153             loadKey("privateKey.bin",PKCS8,RSA);
 154             loadKey("privateKey.bin",PKCS8,RSA);
 155         } 
 156         catch(Exception ex){            
 157             ex.printStackTrace();
 158         }        
 159     }
 160 }

GCJ example desktop app

   1 javac ToolbarFrame1.java BasicWindowMonitor.java # compile
   2 java ToolbarFrame1 # run
   3 

ToolbarFrame1.java

   1 /*
   2 gcj --main=ToolbarFrame1 -g -o ToolbarFrame1 ToolbarFrame1.java BasicWindowMonitor.java
   3  */
   4 import java.awt.*;
   5 import java.awt.event.*;
   6 
   7 public class ToolbarFrame1 extends Frame implements ActionListener {
   8   Button cutButton, copyButton, pasteButton;
   9   
  10   public ToolbarFrame1() {
  11     super("Toolbar Example (AWT)");
  12     setSize(450, 250);
  13     //addWindowListener(new BasicWindowMonitor());
  14     WindowListener wl = new WindowListener(){
  15         public void windowActivated(WindowEvent e){   
  16             System.out.println("Activated");
  17         }
  18 
  19         public void windowClosed(WindowEvent e){
  20             System.out.println("Closed");
  21             System.exit(0);      
  22         }
  23 
  24         public void windowClosing(WindowEvent e){   
  25             Window w = e.getWindow();
  26             w.setVisible(false);
  27             w.dispose();    
  28             System.out.println("Closing");
  29         }
  30 
  31         public void windowDeactivated(WindowEvent e){   
  32             System.out.println("Deactivated");
  33         }
  34 
  35         public void windowDeiconified(WindowEvent e){   
  36             System.out.println("Deiconified");
  37         }
  38 
  39         public void windowIconified(WindowEvent e){   
  40             System.out.println("Iconified");
  41         }
  42 
  43         public void windowOpened(WindowEvent e){   
  44             System.out.println("Opened");
  45         }
  46         
  47     }; 
  48     addWindowListener( wl );
  49   
  50     Panel toolbar = new Panel();
  51     toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));
  52 
  53     cutButton = new Button("Cut");
  54     cutButton.addActionListener(this);
  55     toolbar.add(cutButton);
  56 
  57     copyButton = new Button("Copy");
  58     copyButton.addActionListener(this);
  59     toolbar.add(copyButton);
  60 
  61     pasteButton = new Button("Paste");
  62     pasteButton.addActionListener(this);
  63     toolbar.add(pasteButton);
  64 
  65     add(toolbar, BorderLayout.NORTH);
  66   }
  67 
  68   public void actionPerformed(ActionEvent ae) {
  69     System.out.println(ae.getActionCommand());
  70   }
  71 
  72   public static void main(String args[]) {
  73     ToolbarFrame1 tf1 = new ToolbarFrame1();
  74     tf1.setVisible(true);
  75   }
  76   
  77 }

BasicWindowMonitor.java

   1 import java.awt.event.*;
   2 import java.awt.Window;
   3 
   4 public class BasicWindowMonitor extends WindowAdapter {
   5 
   6   public void windowClosing(WindowEvent e) {
   7     Window w = e.getWindow();
   8     w.setVisible(false);
   9     w.dispose();
  10     System.exit(0);
  11   }
  12 }

Install Oracle jdk8 in Slackware64 15.0

   1 mkdir -p /opt/java
   2 cp jdk-8u162-linux-x64.tar.gz /opt/java/
   3 cd /opt/java/
   4 tar xvzf jdk-8u162-linux-x64.tar.gz 
   5 cd jdk1.8.0_162/bin
   6 ./java

   1 cd ~/Downloads/
   2 wget https://download.java.net/java/GA/jdk17.0.2/dfd4a8d0985749f896bed50d7138ee7f/8/GPL/openjdk-17.0.2_linux-x64_bin.tar.gz 
   3 tar xvzf openjdk-17.0.2_linux-x64_bin.tar.gz 
   4 mv jdk-17.0.2/ ~/
   5 cd ~/jdk-17.0.2/bin/
   6 ./java -version
   7 nano ~/.bashrc 
   8 # PATH=$PATH:~/jdk-17.0.2/bin
   9 source .bashrc 
  10 java -version

Add to .bashrc

   1 PATH=$PATH:/opt/java/jdk1.8.0_162/bin

Float error

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
What Every Computer Scientist Should Know About Floating-Point Arithmetic
IEEE 754
The IEEE standard defines four different precisions: single, double, single-extended, and double-extended.
Since rounding error is inherent in floating-point computation, it is important to have a way to measure this error. 

Generics

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods.

Advantages:

Swing test

   1 /*
   2 javac SwingTest.java
   3 java SwingTest 
   4 */
   5 import javax.swing.*;
   6 import java.awt.event.*;
   7 
   8 public class SwingTest {
   9     private static void createFrame() {
  10         JFrame frame = new JFrame("JFrameTitle");
  11         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  12         frame.setLayout(null);
  13 
  14         JTextField jtf = new JTextField();
  15         jtf.setBounds(5,80,100,25);
  16 
  17         JLabel label = new JLabel("JLabel");
  18         label.setBounds(5,5,100,25); 
  19         JButton button = new JButton("Press me");
  20         button.setBounds(5,35,100,25);
  21         ActionListener al = new ActionListener(){
  22             public void actionPerformed(ActionEvent e){
  23                 System.out.println("Pressed " + jtf.getText() );
  24             }
  25         };
  26         button.addActionListener( al );
  27 
  28         frame.getContentPane().add(label);
  29         frame.getContentPane().add(button);
  30         frame.getContentPane().add(jtf);
  31         frame.pack();
  32         frame.setVisible(true);
  33         frame.setSize(640,480);
  34     }
  35 
  36     public static void main(String[] args) {
  37         createFrame();
  38     }
  39 }

XML signature example

.
├── dummy.xml
├── pom.xml
├── signed.xml
├── src
│   └── main
│       └── java
│           └── org
│               └── allowed
│                   └── bitarus
│                       └── xmlsign
│                           ├── KeyValueKeySelector.java
│                           ├── Main.java
│                           └── SimpleKeySelectorResult.java

pom.xml

   1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   2         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   3         http://maven.apache.org/maven-v4_0_0.xsd">
   4         <modelVersion>4.0.0</modelVersion>
   5         <groupId>org.allowed.bitarus</groupId>
   6         <artifactId>xmlsign</artifactId>
   7         <packaging>jar</packaging>
   8         <version>0.0.1</version>
   9         <name>xmlsign</name>
  10         <url>http://maven.apache.org</url>
  11         <build>
  12                 <plugins>
  13                         <plugin>
  14                                 <artifactId>maven-assembly-plugin</artifactId>
  15                                 <version>2.4</version>
  16                                 <configuration>
  17                                         <descriptorRefs>
  18                                                 <descriptorRef>jar-with-dependencies</descriptorRef>
  19                                         </descriptorRefs>
  20                                         <archive>
  21                                                 <manifest>
  22                                                         <mainClass>org.allowed.bitarus.xmlsign.Main</mainClass>
  23                                                 </manifest>
  24                                         </archive>
  25                                 </configuration>
  26                                 <executions>
  27                                         <execution>
  28                                                 <id>make-assembly</id> 
  29                                                 <phase>package</phase> 
  30                                                 <goals>
  31                                                         <goal>single</goal>
  32                                                 </goals>
  33                                         </execution>
  34                                 </executions>
  35                         </plugin>
  36                 </plugins>
  37         </build>
  38         <dependencies>
  39         </dependencies>
  40 </project>

dummy.xml

   1 <Envelope xmlns="urn:envelope">
   2 </Envelope>

KeyValueKeySelector.java

   1 package org.allowed.bitarus.xmlsign;
   2 
   3 // https://docs.oracle.com/javase/8/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html#wp510726
   4 // https://docs.oracle.com/javase/6/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
   5 import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
   6 import javax.xml.crypto.dsig.XMLSignatureFactory;
   7 import javax.xml.crypto.dsig.SignedInfo;
   8 import javax.xml.crypto.dsig.keyinfo.KeyInfo;
   9 import javax.xml.crypto.dsig.CanonicalizationMethod;
  10 import javax.xml.crypto.dsig.SignatureMethod;
  11 import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
  12 import java.security.NoSuchAlgorithmException;
  13 import java.security.InvalidAlgorithmParameterException;
  14 import javax.xml.crypto.dsig.DigestMethod;
  15 import javax.xml.crypto.dsig.Transform;
  16 import javax.xml.crypto.dsig.spec.TransformParameterSpec;
  17 import javax.xml.crypto.dsig.Reference;
  18 import java.util.Collections;
  19 import java.security.KeyPair;
  20 import java.security.KeyPairGenerator;
  21 import javax.xml.crypto.dsig.keyinfo.KeyValue;
  22 import java.security.KeyException;
  23 import javax.xml.crypto.dsig.XMLSignature;
  24 import javax.xml.crypto.dsig.dom.DOMSignContext;
  25 import javax.xml.parsers.DocumentBuilderFactory;
  26 import javax.xml.parsers.DocumentBuilder;
  27 import java.io.FileInputStream;
  28 import java.io.FileOutputStream;
  29 import java.io.OutputStream;
  30 import org.w3c.dom.Document;
  31 import javax.xml.parsers.ParserConfigurationException;
  32 import java.io.FileNotFoundException;
  33 import org.xml.sax.SAXException;
  34 import javax.xml.crypto.MarshalException;
  35 import java.io.IOException;
  36 import javax.xml.crypto.dsig.XMLSignatureException;
  37 import javax.xml.transform.TransformerFactory;
  38 import javax.xml.transform.Transformer;
  39 import javax.xml.transform.dom.DOMSource;
  40 import javax.xml.transform.stream.StreamResult;
  41 import javax.xml.transform.TransformerConfigurationException;
  42 import javax.xml.transform.TransformerException;
  43 import org.w3c.dom.NodeList;
  44 import java.lang.Exception;
  45 import javax.xml.crypto.dsig.dom.DOMValidateContext;
  46 import java.util.Iterator;
  47 import javax.xml.crypto.KeySelector;
  48 import javax.xml.crypto.AlgorithmMethod;
  49 import javax.xml.crypto.XMLCryptoContext;
  50 import javax.xml.crypto.KeySelectorException;
  51 import java.util.List;
  52 import javax.xml.crypto.XMLStructure;
  53 import javax.xml.crypto.KeySelectorResult;
  54 import java.security.PublicKey;
  55 import java.security.Key;
  56 
  57 
  58 public  class KeyValueKeySelector extends KeySelector {
  59 
  60   public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose,  AlgorithmMethod method,
  61       XMLCryptoContext context)
  62     throws KeySelectorException {
  63 
  64     if (keyInfo == null) {
  65       throw new KeySelectorException("Null KeyInfo object!");
  66     }
  67 
  68     SignatureMethod sm = (SignatureMethod) method;
  69     List list = keyInfo.getContent();
  70 
  71     for (int i = 0; i < list.size(); i++) {
  72       XMLStructure xmlStructure = (XMLStructure) list.get(i);
  73       if (xmlStructure instanceof KeyValue) {
  74         PublicKey pk = null;
  75         try {
  76           pk = ((KeyValue)xmlStructure).getPublicKey();
  77         } catch (KeyException ke) {
  78           throw new KeySelectorException(ke);
  79         }
  80         // make sure algorithm is compatible with method
  81         if (algEquals(sm.getAlgorithm(), pk.getAlgorithm()) ) {
  82           return new SimpleKeySelectorResult(pk);
  83         }
  84       }
  85     }
  86     throw new KeySelectorException("No KeyValue element found!");
  87   }
  88 
  89   boolean algEquals(String algURI, String algName) {
  90     if (algName.equalsIgnoreCase("DSA") &&
  91         algURI.equalsIgnoreCase("http://www.w3.org/2009/xmldsig11#dsa-sha256")) {
  92       return true;
  93     } else if (algName.equalsIgnoreCase("RSA") &&
  94         algURI.equalsIgnoreCase("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256")) {
  95       return true;
  96     } else {
  97       return false;
  98     }
  99   }
 100 } 

Main.java

   1 package org.allowed.bitarus.xmlsign;
   2 
   3 // https://docs.oracle.com/javase/8/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html#wp510726
   4 // https://docs.oracle.com/javase/6/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
   5 import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
   6 import javax.xml.crypto.dsig.XMLSignatureFactory;
   7 import javax.xml.crypto.dsig.SignedInfo;
   8 import javax.xml.crypto.dsig.keyinfo.KeyInfo;
   9 import javax.xml.crypto.dsig.CanonicalizationMethod;
  10 import javax.xml.crypto.dsig.SignatureMethod;
  11 import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
  12 import java.security.NoSuchAlgorithmException;
  13 import java.security.InvalidAlgorithmParameterException;
  14 import javax.xml.crypto.dsig.DigestMethod;
  15 import javax.xml.crypto.dsig.Transform;
  16 import javax.xml.crypto.dsig.spec.TransformParameterSpec;
  17 import javax.xml.crypto.dsig.Reference;
  18 import java.util.Collections;
  19 import java.security.KeyPair;
  20 import java.security.KeyPairGenerator;
  21 import javax.xml.crypto.dsig.keyinfo.KeyValue;
  22 import java.security.KeyException;
  23 import javax.xml.crypto.dsig.XMLSignature;
  24 import javax.xml.crypto.dsig.dom.DOMSignContext;
  25 import javax.xml.parsers.DocumentBuilderFactory;
  26 import javax.xml.parsers.DocumentBuilder;
  27 import java.io.FileInputStream;
  28 import java.io.FileOutputStream;
  29 import java.io.OutputStream;
  30 import org.w3c.dom.Document;
  31 import javax.xml.parsers.ParserConfigurationException;
  32 import java.io.FileNotFoundException;
  33 import org.xml.sax.SAXException;
  34 import javax.xml.crypto.MarshalException;
  35 import java.io.IOException;
  36 import javax.xml.crypto.dsig.XMLSignatureException;
  37 import javax.xml.transform.TransformerFactory;
  38 import javax.xml.transform.Transformer;
  39 import javax.xml.transform.dom.DOMSource;
  40 import javax.xml.transform.stream.StreamResult;
  41 import javax.xml.transform.TransformerConfigurationException;
  42 import javax.xml.transform.TransformerException;
  43 import org.w3c.dom.NodeList;
  44 import java.lang.Exception;
  45 import javax.xml.crypto.dsig.dom.DOMValidateContext;
  46 import java.util.Iterator;
  47 import javax.xml.crypto.KeySelector;
  48 import javax.xml.crypto.AlgorithmMethod;
  49 import javax.xml.crypto.XMLCryptoContext;
  50 import javax.xml.crypto.KeySelectorException;
  51 import java.util.List;
  52 import javax.xml.crypto.XMLStructure;
  53 import javax.xml.crypto.KeySelectorResult;
  54 import java.security.PublicKey;
  55 import java.security.Key;
  56 
  57 public class Main{
  58 
  59     public static void main(String args[]) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
  60         KeyException,ParserConfigurationException,FileNotFoundException,SAXException,MarshalException,
  61         IOException, XMLSignatureException,TransformerConfigurationException, TransformerException, Exception {
  62         DocumentBuilderFactory dbf =  DocumentBuilderFactory.newInstance();
  63         dbf.setNamespaceAware(true);
  64         DocumentBuilder builder = dbf.newDocumentBuilder();
  65         Document doc = builder.parse(new FileInputStream("dummy.xml"));
  66 
  67         KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
  68         kpg.initialize(2048);
  69         KeyPair kp = kpg.generateKeyPair();
  70 
  71         XMLSignatureFactory xs = XMLSignatureFactory.getInstance();
  72         System.out.println(String.format("XMLSignature provider %s",xs.getProvider().getName() ) );
  73         DigestMethod dm = xs.newDigestMethod(DigestMethod.SHA256, null);
  74         Transform transform = xs.newTransform(Transform.ENVELOPED,(TransformParameterSpec) null);
  75 
  76         CanonicalizationMethod cm =  xs.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, 
  77          (C14NMethodParameterSpec) null );
  78         Reference ref = xs.newReference("",dm,Collections.singletonList(transform),null,null );
  79         SignatureMethod sm = xs.newSignatureMethod("http://www.w3.org/2009/xmldsig11#dsa-sha256", null);
  80         SignedInfo sigInfo = xs.newSignedInfo(cm, sm, Collections.singletonList(ref));
  81 
  82         KeyInfoFactory kif = xs.getKeyInfoFactory();
  83         KeyValue kv = kif.newKeyValue(kp.getPublic());
  84         KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); 
  85 
  86         XMLSignature signature = xs.newXMLSignature(sigInfo, ki); 
  87 
  88         DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());
  89         signature.sign(dsc);
  90 
  91         OutputStream os = new FileOutputStream("signed.xml");
  92         TransformerFactory tf = TransformerFactory.newInstance();
  93         Transformer trans = tf.newTransformer();
  94         trans.transform(new DOMSource(doc), new StreamResult(os)); 
  95 
  96         //validate the signed.xml ...
  97         DocumentBuilderFactory otherdbf = DocumentBuilderFactory.newInstance(); 
  98         otherdbf.setNamespaceAware(true); 
  99         DocumentBuilder otherbuilder = otherdbf.newDocumentBuilder();  
 100         Document signedDoc = otherbuilder.parse(new FileInputStream("signed.xml")); 
 101         NodeList nl = signedDoc.getElementsByTagNameNS (XMLSignature.XMLNS, "Signature");
 102         if (nl.getLength() == 0) {
 103             throw new Exception("Cannot find Signature element");
 104         }
 105 
 106         //DOMValidateContext valContext = new DOMValidateContext( new KeyValueKeySelector() , nl.item(0)); 
 107         DOMValidateContext valContext = new DOMValidateContext( kp.getPublic() , nl.item(0)); 
 108         XMLSignatureFactory otherFactory = XMLSignatureFactory.getInstance("DOM"); 
 109         XMLSignature otherSig  = otherFactory.unmarshalXMLSignature(valContext); 
 110         System.out.println( String.format("Is valid? %b", otherSig.validate(valContext) ) );
 111 
 112         boolean sv = otherSig.getSignatureValue().validate(valContext);
 113         System.out.println("signature validation status: " + sv); 
 114 
 115         Iterator i = otherSig.getSignedInfo().getReferences().iterator();
 116         for (int j=0; i.hasNext(); j++) {
 117             boolean refValid = ((Reference)  i.next()).validate(valContext);
 118             System.out.println("ref["+j+"] validity status: " +  refValid);
 119         }
 120 
 121     }
 122 }

SimpleKeySelectorResult.java

   1 package org.allowed.bitarus.xmlsign;
   2 
   3 // https://docs.oracle.com/javase/8/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html#wp510726
   4 // https://docs.oracle.com/javase/6/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
   5 import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
   6 import javax.xml.crypto.dsig.XMLSignatureFactory;
   7 import javax.xml.crypto.dsig.SignedInfo;
   8 import javax.xml.crypto.dsig.keyinfo.KeyInfo;
   9 import javax.xml.crypto.dsig.CanonicalizationMethod;
  10 import javax.xml.crypto.dsig.SignatureMethod;
  11 import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
  12 import java.security.NoSuchAlgorithmException;
  13 import java.security.InvalidAlgorithmParameterException;
  14 import javax.xml.crypto.dsig.DigestMethod;
  15 import javax.xml.crypto.dsig.Transform;
  16 import javax.xml.crypto.dsig.spec.TransformParameterSpec;
  17 import javax.xml.crypto.dsig.Reference;
  18 import java.util.Collections;
  19 import java.security.KeyPair;
  20 import java.security.KeyPairGenerator;
  21 import javax.xml.crypto.dsig.keyinfo.KeyValue;
  22 import java.security.KeyException;
  23 import javax.xml.crypto.dsig.XMLSignature;
  24 import javax.xml.crypto.dsig.dom.DOMSignContext;
  25 import javax.xml.parsers.DocumentBuilderFactory;
  26 import javax.xml.parsers.DocumentBuilder;
  27 import java.io.FileInputStream;
  28 import java.io.FileOutputStream;
  29 import java.io.OutputStream;
  30 import org.w3c.dom.Document;
  31 import javax.xml.parsers.ParserConfigurationException;
  32 import java.io.FileNotFoundException;
  33 import org.xml.sax.SAXException;
  34 import javax.xml.crypto.MarshalException;
  35 import java.io.IOException;
  36 import javax.xml.crypto.dsig.XMLSignatureException;
  37 import javax.xml.transform.TransformerFactory;
  38 import javax.xml.transform.Transformer;
  39 import javax.xml.transform.dom.DOMSource;
  40 import javax.xml.transform.stream.StreamResult;
  41 import javax.xml.transform.TransformerConfigurationException;
  42 import javax.xml.transform.TransformerException;
  43 import org.w3c.dom.NodeList;
  44 import java.lang.Exception;
  45 import javax.xml.crypto.dsig.dom.DOMValidateContext;
  46 import java.util.Iterator;
  47 import javax.xml.crypto.KeySelector;
  48 import javax.xml.crypto.AlgorithmMethod;
  49 import javax.xml.crypto.XMLCryptoContext;
  50 import javax.xml.crypto.KeySelectorException;
  51 import java.util.List;
  52 import javax.xml.crypto.XMLStructure;
  53 import javax.xml.crypto.KeySelectorResult;
  54 import java.security.PublicKey;
  55 import java.security.Key;
  56 
  57 public class SimpleKeySelectorResult implements KeySelectorResult{
  58     private Key key;
  59 
  60     public SimpleKeySelectorResult(Key key){
  61       this.key= key;
  62     }
  63 
  64     public Key getKey(){
  65       return this.key;
  66     }
  67 }

Add numbers console

   1 javac AddNumbers.java
   2 java  -Duser.language=pt -Duser.country=PT AddNumbers
   3 # user country and language set the decimal separator as , (comma) for Portugal
   4 

AddNumbers.java

   1 import java.util.Scanner;
   2 
   3 public class AddNumbers {
   4 
   5     public static double readDouble() {
   6         boolean gotException = true;
   7         double value = -1.0;
   8 
   9         while (gotException) {
  10             try {
  11                 Scanner scanner = new Scanner(System.in);
  12                 value = scanner.nextDouble();
  13                 gotException = false;
  14             } catch (Exception ex) {
  15                 System.out.println("Try again");
  16             }
  17         }
  18         return value;
  19 
  20     }
  21 
  22     public static void main(String[] args) {
  23         double first = -1;
  24         double second = -1;
  25         System.out.println("Input first number:");
  26         first = readDouble();
  27         System.out.println("Input second number:");
  28 
  29         second = readDouble();
  30         System.out.printf("%.2f%n",first + second);
  31     }
  32 }

Date format

   1 import java.util.Date;
   2 import java.text.SimpleDateFormat;
   3 
   4 class Main {  
   5   public static void main(String args[]) { 
   6     Date d = new Date();  
   7     SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:MM");
   8     System.out.println("Hello, world! " + sdf.format(d) ); 
   9   } 
  10 }

Java (last edited 2024-03-14 22:10:50 by vitor)