Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.findcomputerstuff.nips; import nfp.ssm.core.SSMLib; import org.apache.commons.lang3.StringUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; /** * * @author oyk */ public class DefaultSecurityModule implements ISecurityModule { public String getPrivateKeyFile() { return privateKeyFile; } public void setPrivateKeyFile(String filePath) { this.privateKeyFile = filePath; } public String getPublicKeyFile() { return publicKeyFile; } public void setPublicKeyFile(String filePath) { this.publicKeyFile = filePath; } public String getPrivateKeyPassword() { return privateKeyPassword; } public void setPrivateKeyPassword(String password) { this.privateKeyPassword = password; } private String privateKeyFile; private String publicKeyFile; private String privateKeyPassword; @Override public String encryptMessage(String message) throws SsmEncryptionException { return processMessage(message, MessageAction.ENCRYPT); } @Override public String decryptMessage(String message) throws SsmEncryptionException { if (StringUtils.isEmpty(message)) throw new SsmEncryptionException("Cipher to be decrypted cannot be null or empty"); if (StringUtils.isEmpty(privateKeyPassword)) throw new SsmEncryptionException("Private key password specified is blank"); return processMessage(message, MessageAction.DECRYPT); } private enum MessageAction { ENCRYPT, DECRYPT } private String processMessage(String message, MessageAction action) { String outStr = null; SSMLib ssm = new nfp.ssm.core.SSMLib(publicKeyFile, privateKeyFile); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { PrintStream console = System.out; try (PrintStream ps = new PrintStream(os)) { System.setOut(ps); /* redirect stdout */ } switch (action) { case DECRYPT: outStr = ssm.decryptFile(message, privateKeyPassword); break; case ENCRYPT: outStr = ssm.encryptMessage(message); break; } System.out.flush(); System.setOut(console); /* restore stdout */ if (StringUtils.isBlank(outStr)) throw new SsmEncryptionException(os.toString()); } catch (IOException e) { e.printStackTrace(); } return outStr; } }