Bash: Passphrase encryption program

Bash: Passphrase encryption program
I wrote this a while back while playing with gpg.
#!/bin/bash
# Passphrase encryption program
# Created by Dave Crouse 01-13-2006
# Reads input from text editor and encrypts to screen.
clear
echo " Passphrase Encryption Program";
echo "--------------------------------------------------"; echo "";
which $EDITOR &>/dev/null
if [ $? != "0" ];
then
echo "It appears that you do not have a text editor set in your .bashrc file.";
echo "What editor would you like to use ? " ;
read EDITOR ; echo "";
fi
echo "Enter the name/comment for this message :"
read comment
$EDITOR passphraseencryption
gpg --armor --comment "$comment" --no-options --output passphraseencryption.gpg --symmetric passphraseencryption
shred -u passphraseencryption ; clear
echo "Outputting passphrase encrypted message"; echo "" ; echo "" ;
cat passphraseencryption.gpg ; echo "" ; echo "" ;
shred -u passphraseencryption.gpg ;
exit
After you run the program, it outputs something like this.......
-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.4.2 (GNU/Linux)
Comment: KEY: Linux is cool
jA0EAwMC5l8nNDuWf2lgyaJl2VwbtOWttdVlNC2wtpI22jcRkJOUnph/xzvYoac1
zXznkxunRyT7elT668dTSREdKrZ7H7geGtVkeu2eRFALlXkDVSg5m80nntGzG88r
6UGjqIG3nOjztOOGrOODDTYidCoPYwEAaVZADU827lpycUeqiA9+zH5oQl9eFHEO
cYK9G2LnWR0CMY7KFadocPX3o3u1CBeZJsObTonFIty7FYQ=
=mlIy
-----END PGP MESSAGE-----
The "key" for this message is "Linux is cool" .... of course you wouldn't put the key in the name/comment section like i did, but mine was for illustrative purposes only.
I'm sure the program could be improved, use the temp file/ do more error checking etc... but this was just a "quick-n-dirty" way to create an encrypted message
Hope you like it.

I didn't test it, just a style suggestion:
Instead of:
which $EDITOR &>/dev/null
if [ $? != "0" ];
then
use:
if [ -z "$EDITOR" ]; then
# $EDITOR not set
And you don't need "exit" at the end or ";" at the end of a line

Similar Messages

  • Encryption Program

    Ok, so here's the deal:
    For school I have to create an encryption program that will read a string from the user, ask them for an alphabet that it will use to encrypt it then encrypt the phrase. This is my code:
    * This program asks the user for a phrase and encrypts it
    * @author Michael S
    * @version v13.37 March 4, 2008
    import java.io.*;
    import java.lang.*;
    public class EncryptA
        public static void main (String[] args) { // main method string
          String temp1;
          String temp2;
          String phrase;
          String encphrase;
          String encAlph[] = {"","","","","","","","","","","","","","","","","","","","","","","","","",""};
          String encalphrase;
          int k; 
          int i;
          int q;
          String phtemp;
          String altemp;
          int phraselength;
          String alphaArray[] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}; // the elements in the main array
          //  prompt the user to enter their word(s)
          System.out.print("Enter your phrase to be encrypted, then hit enter."); // Asks the user to enter the phrase
          System.out.println(); // prints a blank line
          //  open up standard input
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          //  read the phrase from the command-line; need to use try/catch with the
          //  readLine() method
          temp1 = ""; // initilizing temp
          System.out.println(); // print a blank line
          try { // try
          temp1 = br.readLine(); // temp is equal to what the user just entered            
          } // end of try
          catch (IOException ioe) { // catch the exceptions
             System.out.print("You're doing it wrong, try again."); // give the user a message telling them that they need to try again
             System.out.println(); // print a blank line
          } // end of catch
          catch (NumberFormatException e) { // catch the numeric exceptions
             System.out.print("You're doing it wrong, try again."); // give the user a message telling them that they need to try again
             System.out.println(); // print a blank line
          } // end of catch
          phraselength = temp1.length(); // length is equal to the number of characters in the phrase
          phrase = temp1;
          //  prompt the user to enter their word(s)
          System.out.println(); // blank line
          System.out.print("Enter the encrypted alphabet you want to use, then hit enter."); // Asks the user to enter the phrase
          System.out.println(); // prints a blank line
          temp2 = ""; // initilizing temp
          System.out.println(); // print a blank line
          try { // try
          temp2 = br.readLine(); // temp is equal to what the user just entered            
          } // end of try
          catch (IOException ioe) { // catch the exceptions
             System.out.print("You're doing it wrong, try again."); // give the user a message telling them that they need to try again
             System.out.println(); // print a blank line
          } // end of catch
          catch (NumberFormatException e) { // catch the numeric exceptions
             System.out.print("You're doing it wrong, try again."); // give the user a message telling them that they need to try again
             System.out.println(); // print a blank line
          } // end of catch
          encalphrase = temp2;
          q = 0;
          while (q < 26) {
          encAlph[q] = "" + encalphrase.charAt(q); // assigning temp2 to encAlph at "a"
          q++; // add 1 to q
          i = 0;
          k = 0;
          encphrase = "";
          while (i < phraselength) {
              while (k < 26) {
                  phtemp = "" + phrase.charAt(i);
                  altemp = alphaArray[k];
                  if (phtemp.compareTo(altemp) != 0) {
                      encphrase = "" + encphrase;
                  if (phtemp.equals(altemp)) {
                      encphrase = "" + encphrase + encAlph[k];
                  if (phtemp.equalsIgnoreCase(" ")) {
                      encphrase = "" + encphrase + " ";
                    k++;   
                i++;
            } // end of beginning while
          k = 0;
          System.out.println(); // print a blank line
          System.out.println("This is what you entered: " + temp1); // tells the user that this is what they entered
          System.out.println("Your phrase you entered has " + phraselength + " characters.");
          System.out.print("This is the contents of encAlph[]: ");
          while ( k < 26 ) {
          System.out.print(encAlph[k]);
          k++;
          System.out.println();
          System.out.println("Your encrypted phrase is: " + encphrase);
          i = 0;
    }When I compile it, I get no errors, and this is what the terminal window looks like:
    Enter your phrase to be encrypted, then hit enter.
    hello
    Enter the encrypted alphabet you want to use, then hit enter.
    qwertyuiopasdfghjklzxcvbnm
    This is what you entered: hello
    Your phrase you entered has 5 characters.
    This is the contents of encAlph[]: qwertyuiopasdfghjklzxcvbnm
    Your encrypted phrase is: iThe problem is, I get "i" as the encrypted phrase, when I didn't even enter an "i". This applies for any phrase I enter. Any idea what is wrong and how to fix it? Or another way to do encryption? Any help at all is appreciated :)

    Ok, I still don't understand what you people are trying to say. I know why it isn't working, the loop with the variable "q" isn't looping for some reason. I have it set up 100% correct, and it isn't looping. Can anyone tell me why it is not looping?
    q = 0;
          k = 0;
          while (q < 5) {
              while (k < 26) {
                  phtemp = "" + phrase.charAt(q);
                  altemp = alphaArray[k];
                  if (phtemp.compareTo(altemp) != 0) {
                      System.out.println("No change.");
                  if (phtemp.equals(altemp)) {
                      encphrase = "" + encphrase + encAlph[k];
                      System.out.println("Strings are equal.");
                  if (phtemp.equalsIgnoreCase(" ")) {
                      encphrase = "" + encphrase + " ";
                      System.out.println("There is a space.");
                    k++;
                } // end of k while
            q++;
        }// end of q while

  • Encrypting Programs using 2 keywords(2 square cipher)?

    Hello, I am trying to create a program that can encrypt and save files using 2 keywords. (it's part of a course I'm starting). At the moment, I have created a program that can encrypt messages with ONE keyword. 
    If someone could provide a solution to my problem - that would be absolutely wonderful. 
    thanks.

    This is what I've done so far ; 
    it encrypted messages using only ONE keyword
    'text window setup
    TextWindow.Title = "Encryption Program - Task 2"
    'get message
    start: 
    TextWindow.ForegroundColor = "green"
    TextWindow.BackgroundColor = "blue"
    TextWindow.WriteLine("Please enter your message.")
    Message = TextWindow.Read()
    Characters = Text.GetSubText(Message,1,1)
    WordCharacterCode = Text.GetCharacterCode(Characters)
    'message error check
    If WordCharacterCode < 65 Or WordCharacterCode > 122 Or WordCharacterCode < 97 And WordCharacterCode> 90 Then
      TextWindow.ForegroundColor = "red"
      TextWindow.WriteLine("ERROR - Please try again")
      Goto start
      EndIf
    'get keyword
    TextWindow.WriteLine("Please enter a keyword")
    key = TextWindow.Read()
    KeyCharacter = Text.GetSubText(key,1,1)
    KeyCharacterCode = Text.GetCharacterCode(KeyCharacter)
    'keyword error check
    If KeyCharacterCode < 65 Or KeyCharacterCode > 122 Or KeyCharacterCode < 97 And KeyCharacterCode > 90 Then 
       TextWindow.ForegroundColor = "red"
      TextWindow.WriteLine("**ERROR - Please try again**")
      Goto start
    Else 
      EncryptLowerCase()
    EndIf
    'suborutine - encrypts message
    Sub EncryptLowerCase 
    TextWindow.ForegroundColor = "green"
    TextWindow.BackgroundColor = "black"
    count = 1 
    While Text.GetLength(keyword) < Text.GetLength(Message)
      If count > Text.GetLength(key) Then 
        count = 1
      EndIf 
      keyletter = Text.GetSubText(key,count,1)
      keyword = keyword + keyletter
      count = count + 1
    EndWhile
    For i = 1 To Text.GetLength(Message)
      charscode = Text.GetCharacterCode(Text.GetSubText(Message,i,1)) - 96
      keycharscode = Text.GetCharacterCode(Text.GetSubText(keyword,i,1)) - 96
      encryptedchar = Text.GetCharacter(Math.Remainder(keycharscode + charscode,26)+96)
      encrypted = encrypted + encryptedchar
    EndFor
    'text window setup
    TextWindow.Title = "Encryption Program - Task 2"
    'get message
    start: 
    TextWindow.ForegroundColor = "green"
    TextWindow.BackgroundColor = "blue"
    TextWindow.WriteLine("Please enter your message.")
    Message = TextWindow.Read()
    Characters = Text.GetSubText(Message,1,1)
    WordCharacterCode = Text.GetCharacterCode(Characters)
    'message error check
    If WordCharacterCode < 65 Or WordCharacterCode > 122 Or WordCharacterCode < 97 And WordCharacterCode> 90 Then
      TextWindow.ForegroundColor = "red"
      TextWindow.WriteLine("ERROR - Please try again")
      Goto start
      EndIf
    'get keyword
    TextWindow.WriteLine("Please enter a keyword")
    key = TextWindow.Read()
    KeyCharacter = Text.GetSubText(key,1,1)
    KeyCharacterCode = Text.GetCharacterCode(KeyCharacter)
    'keyword error check
    If KeyCharacterCode < 65 Or KeyCharacterCode > 122 Or KeyCharacterCode < 97 And KeyCharacterCode > 90 Then 
       TextWindow.ForegroundColor = "red"
      TextWindow.WriteLine("**ERROR - Please try again**")
      Goto start
    Else 
      EncryptLowerCase()
    EndIf
    'suborutine - encrypts message
    Sub EncryptLowerCase 
    TextWindow.ForegroundColor = "green"
    TextWindow.BackgroundColor = "black"
    count = 1 
    While Text.GetLength(keyword) < Text.GetLength(Message)
      If count > Text.GetLength(key) Then 
        count = 1
      EndIf 
      keyletter = Text.GetSubText(key,count,1)
      keyword = keyword + keyletter
      count = count + 1
    EndWhile
    For i = 1 To Text.GetLength(Message)
      charscode = Text.GetCharacterCode(Text.GetSubText(Message,i,1)) - 96
      keycharscode = Text.GetCharacterCode(Text.GetSubText(keyword,i,1)) - 96
      encryptedchar = Text.GetCharacter(Math.Remainder(keycharscode + charscode,26)+96)
      encrypted = encrypted + encryptedchar
    EndFor
    'text window setup
    TextWindow.Title = "Encryption Program - Task 2"
    'get message
    start: 
    TextWindow.ForegroundColor = "green"
    TextWindow.BackgroundColor = "blue"
    TextWindow.WriteLine("Please enter your message.")
    Message = TextWindow.Read()
    Characters = Text.GetSubText(Message,1,1)
    WordCharacterCode = Text.GetCharacterCode(Characters)
    'message error check
    If WordCharacterCode < 65 Or WordCharacterCode > 122 Or WordCharacterCode < 97 And WordCharacterCode> 90 Then
      TextWindow.ForegroundColor = "red"
      TextWindow.WriteLine("ERROR - Please try again")
      Goto start
      EndIf
    'get keyword
    TextWindow.WriteLine("Please enter a keyword")
    key = TextWindow.Read()
    KeyCharacter = Text.GetSubText(key,1,1)
    KeyCharacterCode = Text.GetCharacterCode(KeyCharacter)
    'keyword error check
    If KeyCharacterCode < 65 Or KeyCharacterCode > 122 Or KeyCharacterCode < 97 And KeyCharacterCode > 90 Then 
       TextWindow.ForegroundColor = "red"
      TextWindow.WriteLine("**ERROR - Please try again**")
      Goto start
    Else 
      EncryptLowerCase()
    EndIf
    'suborutine - encrypts message
    Sub EncryptLowerCase 
    TextWindow.ForegroundColor = "green"
    TextWindow.BackgroundColor = "black"
    count = 1 
    While Text.GetLength(keyword) < Text.GetLength(Message)
      If count > Text.GetLength(key) Then 
        count = 1
      EndIf 
      keyletter = Text.GetSubText(key,count,1)
      keyword = keyword + keyletter
      count = count + 1
    EndWhile
    For i = 1 To Text.GetLength(Message)
      charscode = Text.GetCharacterCode(Text.GetSubText(Message,i,1)) - 96
      keycharscode = Text.GetCharacterCode(Text.GetSubText(keyword,i,1)) - 96
      encryptedchar = Text.GetCharacter(Math.Remainder(keycharscode + charscode,26)+96)
      encrypted = encrypted + encryptedchar
    EndFor
    'text window setup
    TextWindow.Title = "Encryption Program - Task 2"
    'get message
    start: 
    TextWindow.ForegroundColor = "green"
    TextWindow.BackgroundColor = "blue"
    TextWindow.WriteLine("Please enter your message.")
    Message = TextWindow.Read()
    Characters = Text.GetSubText(Message,1,1)
    WordCharacterCode = Text.GetCharacterCode(Characters)
    'message error check
    If WordCharacterCode < 65 Or WordCharacterCode > 122 Or WordCharacterCode < 97 And WordCharacterCode> 90 Then
      TextWindow.ForegroundColor = "red"
      TextWindow.WriteLine("ERROR - Please try again")
      Goto start
      EndIf
    'get keyword
    TextWindow.WriteLine("Please enter a keyword")
    key = TextWindow.Read()
    KeyCharacter = Text.GetSubText(key,1,1)
    KeyCharacterCode = Text.GetCharacterCode(KeyCharacter)
    'keyword error check
    If KeyCharacterCode < 65 Or KeyCharacterCode > 122 Or KeyCharacterCode < 97 And KeyCharacterCode > 90 Then 
       TextWindow.ForegroundColor = "red"
      TextWindow.WriteLine("**ERROR - Please try again**")
      Goto start
    Else 
      EncryptLowerCase()
    EndIf
    'suborutine - encrypts message
    Sub EncryptLowerCase 
    TextWindow.ForegroundColor = "green"
    TextWindow.BackgroundColor = "black"
    count = 1 
    While Text.GetLength(keyword) < Text.GetLength(Message)
      If count > Text.GetLength(key) Then 
        count = 1
      EndIf 
      keyletter = Text.GetSubText(key,count,1)
      keyword = keyword + keyletter
      count = count + 1
    EndWhile
    For i = 1 To Text.GetLength(Message)
      charscode = Text.GetCharacterCode(Text.GetSubText(Message,i,1)) - 96
      keycharscode = Text.GetCharacterCode(Text.GetSubText(keyword,i,1)) - 96
      encryptedchar = Text.GetCharacter(Math.Remainder(keycharscode + charscode,26)+96)
      encrypted = encrypted + encryptedchar
    EndFor

  • Encryption program does not work in IBM JDK

    Hi
    I have a encrypt, decrypt program, which does not work in IBM JDK
    the code is as below, it gives PBEWithMD5AndDES does not exist kind of error when running with IBM JDK
    import java.io.UnsupportedEncodingException;
    import java.security.spec.AlgorithmParameterSpec;
    import java.security.spec.KeySpec;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    public class MapsPasswordUtil
         Cipher ecipher;
         Cipher dcipher;
         // 8-byte Salt
         byte[] salt = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
                   (byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03 };
         // Iteration count
         int iterationCount = 19;
         public MapsPasswordUtil(String passPhrase)
              try
                   KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt,
                             iterationCount);
                   SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
                             .generateSecret(keySpec);
                   ecipher = Cipher.getInstance(key.getAlgorithm());
                   dcipher = Cipher.getInstance(key.getAlgorithm());
                   // Prepare the parameter to the ciphers
                   AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
                             iterationCount);
                   // Create the ciphers
                   ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
                   dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
              } catch (java.security.InvalidAlgorithmParameterException e)
                   e.printStackTrace();
              } catch (java.security.spec.InvalidKeySpecException e)
                   e.printStackTrace();
              } catch (javax.crypto.NoSuchPaddingException e)
                   e.printStackTrace();
              } catch (java.security.NoSuchAlgorithmException e)
                   e.printStackTrace();
              } catch (java.security.InvalidKeyException e)
                   e.printStackTrace();
         public String encrypt(String str)
              try
                   // Encode the string into bytes using utf-8
                   byte[] utf8 = str.getBytes("UTF8");
                   // Encrypt
                   byte[] enc = ecipher.doFinal(utf8);
                   // Encode bytes to base64 to get a string
                   return new sun.misc.BASE64Encoder().encode(enc);
              } catch (javax.crypto.BadPaddingException e)
                   e.printStackTrace();
              } catch (IllegalBlockSizeException e)
                   e.printStackTrace();
              } catch (UnsupportedEncodingException e)
                   e.printStackTrace();
              return null;
         public String decrypt(String str)
              try
                   // Decode base64 to get bytes
                   byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
                   // Decrypt
                   byte[] utf8 = dcipher.doFinal(dec);
                   // Decode using utf-8
                   return new String(utf8, "UTF8");
              } catch (javax.crypto.BadPaddingException e)
                   e.printStackTrace();
              } catch (IllegalBlockSizeException e)
                   e.printStackTrace();
              } catch (UnsupportedEncodingException e)
                   e.printStackTrace();
              } catch (java.io.IOException e)
                   e.printStackTrace();
              return null;
    }

    Works for me with the latest IBM JDK. You will need to specify your context i.e. what platform, what JDK/JRE etc etc etc.
    P.S. That exception handling is rubbish.
    Edited by: sabre150 on Mar 23, 2009 6:01 AM
    I suspect that you are using JDK 1.5 and that you have fallen foul of the bug where key.getAlgorithm() does net return the correct value. You get round this by specifying it as             SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
                ecipher = Cipher.getInstance("PBEWithMD5AndDES");Of course if you are clever you will just define a static final constant for this algorithm.
    Edited by: sabre150 on Mar 23, 2009 6:09 AM

  • Best practice for if/else when one outcome results in exit [Bash]

    I have a bash script with a lot of if/else constructs in the form of
    if <condition>
    then
    <do stuff>
    else
    <do other stuff>
    exit
    fi
    This could also be structured as
    if ! <condition>
    then
    <do other stuff>
    exit
    fi
    <do stuff>
    The first one seems more structured, because it explicitly associates <do stuff> with the condition.  But the second one seems more logical because it avoids explicitly making a choice (then/else) that doesn't really need to be made.
    Is one of the two more in line with "best practice" from pure bash or general programming perspectives?

    I'm not sure if there are 'formal' best practices, but I tend to use the latter form when (and only when) it is some sort of error checking.
    Essentially, this would be when <do stuff> was more of the main purpose of the script, or at least that neighborhood of the script, while <do other stuff> was mostly cleaning up before exiting.
    I suppose more generally, it could relate to the size of the code blocks.  You wouldn't want a long involved <do stuff> section after which a reader would see an "else" and think 'WTF, else what?'.  So, perhaps if there is a substantial disparity in the lengths of the two conditional blocks, put the short one first.
    But I'm just making this all up from my own preferences and intuition.
    When nested this becomes more obvious, and/or a bigger issue.  Consider two scripts:
    if [[ test1 ]]
    then
    if [[ test2 ]]
    then
    echo "All tests passed, continuing..."
    else
    echo "failed test 2"
    exit
    fi
    else
    echo "failed test 1"
    fi
    if [[ ! test1 ]]
    then
    echo "failed test 1"
    exit
    fi
    if [[ ! test2 ]]
    then
    echo "failed test 2"
    exit
    fi
    echo "passed all tests, continuing..."
    This just gets far worse with deeper levels of nesting.  The second seems much cleaner.  In reality though I'd go even further to
    [[ ! test1 ]] && echo "failed test 1" && exit
    [[ ! test2 ]] && echo "failed test 2" && exit
    echo "passed all tests, continuing..."
    edit: added test1/test2 examples.
    Last edited by Trilby (2012-06-19 02:27:48)

  • How to use the same keypair for both encrypt/decryprt-SunPKCS#11

    Dear All,
    Subject: To access iKey 2032 token, to retrieve public/private key from iKey 2032 token using pkcs#11 in sdk1.5, to encrypt/decrypt files.
    When I separate the encrypt and decrypt part of java program, encryption program works well, whereas decryption program does not decrypt anything in the decrypt file (But there is no error). I printed out the public and private key in both encrypt and decrypt part of java program, its displayed differently::
    Encrypt program:
    SunPKCS11-rainbow_token RSA public key, 1024 bits (id 10, session object)
    modulus: 114338469922835728259534620463489934081917342509275191892563243582065
    74380495029336519036972702864998634664269499641616889325482699399559620370181624
    72068116957594402738459932902481604823224406859575930392708524033619120886256353
    58738237376491107769961041015109436347533548940674900728805627968145581222172729
    public exponent: 65537
    SunPKCS11-rainbow_token RSA private key, 1024 bits (id 11, session object, sensi
    tive, unextractable)
    Decrypt Program::
    SunPKCS11-rainbow_token RSA public key, 1024 bits (id 12, session object)
    modulus: 138556361758970660122782926386849783732271581948935425587968692317930
    09262429353977097956605140384961825974398004270547046620971835394362397699233738
    54481804748731546655197744692886754946373745924825650876065903334173666990347814
    83727290962956934521650035029131176614982652900659797194703065074407857754883163
    public exponent: 65537
    SunPKCS11-rainbow_token RSA private key, 1024 bits (id 13, session object, sensi
    tive, unextractable)
    I suspect that every time program generates different set of key, therefore we need to store the generated key during encryption part (i believe it is to be in the keystore) and to use the same for decryption part. Could you please give me a tips how to do this?
    Encrypt Program ::
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import java.text.*;
    import java.math.*;
    import java.security.*;
    import java.security.cert.*;
    import java.security.interfaces.*;
    import javax.crypto.interfaces.*;
    import javax.net.ssl.*;
    import javax.crypto.*;
    import javax.crypto.spec.DESKeySpec;
    import java.security.KeyStore.*;
    * A class of Encrypt.
    public class Encrypt
    public Encrypt(){}
    public void loginToken() {
         Provider p = new sun.security.pkcs11.SunPKCS11(MQConfig.getvalue("SecurityPropertyPath"));
         Security.addProvider(p);
         KeyStore ks = null;
         try{
              String password = General.ReadFiles(MQConfig.getvalue("logFilePath"),"Simple");
              password = password.trim();
              char pin[] = password.toCharArray();
              ks = KeyStore.getInstance("pkcs11");
              ks.load(null,pin);
         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA",p);
              KeyPair kp = kpg.genKeyPair();
              kpg.initialize(1024, new java.security.SecureRandom());
              FileInputStream in = new FileInputStream("C:\\ReportDBBE.properties");
              FileOutputStream out = new FileOutputStream("C:\\ReportDBAE.properties");
              Cipher cp=Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
              cp.init(cp.ENCRYPT_MODE,kp.getPublic());
              CipherOutputStream cout=new CipherOutputStream(out,cp);
              byte[] input=new byte[8];
              int byteread=in.read(input);
              while(byteread!=-1){
                   cout.write(input,0,byteread);
                   byteread=in.read(input);
              cout.flush();
              in.close();
              cout.close();
         catch(NoSuchAlgorithmException nsae)
         System.out.println("No Such Algorithm Exception " + nsae.getMessage());
         catch(NoSuchPaddingException nspe)
         System.out.println("No Such Padding Exception " + nspe.getMessage());
         catch(InvalidKeyException ike)
         System.out.println("Invalid Key Exception " + ike.getMessage());
         catch(IllegalStateException ise)
         System.out.println("Illegal State Exception " + ise.getMessage());
         catch(KeyStoreException kse)
         System.out.println("Key Store Exception " + kse.getMessage());
         catch(CertificateException ce)
         System.out.println("Certificate Exception " + ce.getMessage());
         catch(IOException ioe)
         System.out.println("IO Exception " + ioe.getMessage());
    public static void main (String args[]) throws Exception {
         try{
         Encrypt tl = new Encrypt();
         tl.loginToken();
         }catch(Exception e){
         e.printStackTrace();
    Decrypt Program ::
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import java.text.*;
    import java.math.*;
    import java.security.*;
    import java.security.cert.*;
    import java.security.interfaces.*;
    import javax.crypto.interfaces.*;
    import javax.net.ssl.*;
    import javax.crypto.*;
    import javax.crypto.spec.DESKeySpec;
    import java.security.KeyStore.*;
    * A class of Decrypt.
    public class Decrypt
    public Decrypt(){}
    public void loginToken() {
         Provider p = new sun.security.pkcs11.SunPKCS11(MQConfig.getvalue("SecurityPropertyPath"));
         Security.addProvider(p);
         KeyStore ks = null;
         try{
              String password = General.ReadFiles(MQConfig.getvalue("logFilePath"),"Simple");
              password = password.trim();
              char pin[] = password.toCharArray();
              ks = KeyStore.getInstance("pkcs11");
              ks.load(null,pin);
         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA",p);
              KeyPair kp = kpg.genKeyPair();
              kpg.initialize(1024, new java.security.SecureRandom());
              FileInputStream in1 = new FileInputStream("C:\\ReportDBAE.properties");
              FileOutputStream out1 = new FileOutputStream("C:\\ReportDBAD.properties");
              Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
              AlgorithmParameters algParams = cipher.getParameters();
              cipher.init(Cipher.DECRYPT_MODE,kp.getPrivate(),algParams);
              CipherInputStream cin1=new CipherInputStream(in1,cipher);
              byte[] input1=new byte[8];
              int byteread1=cin1.read(input1);
              while(byteread1!=-1){
                   out1.write(input1,0,byteread1);
                   byteread1=cin1.read(input1);
              out1.flush();
              in1.close();
              out1.close();
              cin1.close();
         catch(NoSuchAlgorithmException nsae)
         System.out.println("No Such Algorithm Exception " + nsae.getMessage());
         catch(NoSuchPaddingException nspe)
         System.out.println("No Such Padding Exception " + nspe.getMessage());
         catch(InvalidKeyException ike)
         System.out.println("Invalid Key Exception " + ike.getMessage());
         catch(IllegalStateException ise)
         System.out.println("Illegal State Exception " + ise.getMessage());
         catch(InvalidAlgorithmParameterException iape)
         System.out.println("Invalid Algorithm ParameterException " + iape.getMessage());
         catch(KeyStoreException kse)
         System.out.println("Key Store Exception " + kse.getMessage());
         catch(CertificateException ce)
         System.out.println("Certificate Exception " + ce.getMessage());
         catch(IOException ioe)
         System.out.println("IO Exception " + ioe.getMessage());
    public static void main (String args[]) throws Exception {
         try{
         Decrypt tl = new Decrypt();
         tl.loginToken();
         }catch(Exception e){
         e.printStackTrace();
    Configuration file::
    name = rainbow_token
    library = c:\winnt\system32\dkck201.dll
    attributes(*,CKO_PRIVATE_KEY,*) = {
    CKA_SIGN = true
    attributes(*,CKO_PRIVATE_KEY,CKK_DH) = {
    CKA_SIGN = null
    attributes(*,CKO_PRIVATE_KEY,CKK_RSA) = {
    CKA_DECRYPT = true
    }

    Hi all,
    Now i manage to use the same keypair for both encrypt/decryprt-SunPKCS#11. Below is my code woks well. In my code i hard coded alias name of certificate, did anyone knows how to read alias name of certificate from iKey token 2032??
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import java.text.*;
    import java.math.*;
    import java.security.*;
    import java.security.cert.*;
    import java.security.interfaces.*;
    import javax.crypto.interfaces.*;
    import javax.net.ssl.*;
    import javax.crypto.*;
    import javax.crypto.spec.DESKeySpec;
    import java.security.KeyStore.*;
    * A class of Encrypt.
    public class Encrypt
    public Encrypt(){}
    public void loginToken() {
         Provider p = new sun.security.pkcs11.SunPKCS11(MQConfig.getvalue("SecurityPropertyPath"));
         String myAlias = "349eefd1-845b-4ba4-9f88-06e9f5cb82f6";
         /** to view alias name
         keytool -list -v -keystore NONE -storetype PKCS11 -storepass PASSWORD
         Security.addProvider(p);
         KeyStore ks = null;
         PrivateKey privKey = null;
         PublicKey pubKey = null;
         try{
              String password = General.ReadFiles(MQConfig.getvalue("logFilePath"),"Simple");
              password = password.trim();
              char pin[] = password.toCharArray();
              ks = KeyStore.getInstance("pkcs11");
              ks.load(null,pin);
              java.security.cert.Certificate cert = ks.getCertificate(myAlias);
              Key key = ks.getKey(myAlias, pin);
              if(key != null) {
                   System.out.println("key class: " + key.getClass().getName()); // -> sun.security.pkcs11.P11Key$P11PrivateKey
                   System.out.println("key bytes: " + key.getEncoded()); // -> null!!!!!!!
         if(PrivateKey.class.isInstance(key)) {
         privKey = (PrivateKey)key;
         System.out.println("algo: " + privKey.getAlgorithm()); // -> RSA
         //Signature rsasig = Signature.getInstance("SHA1withRSA");
         //rsasig.initSign(privKey);
         //rsasig.update(data.getBytes());
         //byte[] sigBytes = rsasig.sign();
         pubKey = cert.getPublicKey();
         //System.out.println("signed bytes: " +sigBytes);
         //return sigBytes;
         //KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA",p);
              //KeyPair kp = kpg.genKeyPair();
              //KeyPair kp = kpg.generateKeyPair();
              //kpg.initialize(1024, new java.security.SecureRandom());
              FileInputStream in = new FileInputStream("C:\\ReportDBBE.properties");
              FileOutputStream out = new FileOutputStream("C:\\ReportDBAE.properties");
              Cipher cp=Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
    //cp.init(cp.ENCRYPT_MODE,kp.getPublic());
              cp.init(cp.ENCRYPT_MODE,pubKey);
              CipherOutputStream cout=new CipherOutputStream(out,cp);
              byte[] input=new byte[8];
              int byteread=in.read(input);
              while(byteread!=-1){
                   cout.write(input,0,byteread);
                   byteread=in.read(input);
              cout.flush();
              in.close();
              cout.close();
         catch(NoSuchAlgorithmException nsae)
         System.out.println("No Such Algorithm Exception " + nsae.getMessage());
         catch(NoSuchPaddingException nspe)
         System.out.println("No Such Padding Exception " + nspe.getMessage());
         catch(InvalidKeyException ike)
         System.out.println("Invalid Key Exception " + ike.getMessage());
         ike.printStackTrace();
         catch(IllegalStateException ise)
         System.out.println("Illegal State Exception " + ise.getMessage());
         catch(KeyStoreException kse)
         System.out.println("Key Store Exception " + kse.getMessage());
         catch(CertificateException ce)
         System.out.println("Certificate Exception " + ce.getMessage());
         catch(IOException ioe)
         System.out.println("IO Exception " + ioe.getMessage());
         catch(UnrecoverableKeyException unrke)
         System.out.println("Unrecoverable Key Exception " + unrke.getMessage());
    public static void main (String args[]) throws Exception {
         try{
         Encrypt tl = new Encrypt();
         tl.loginToken();
         }catch(Exception e){
         e.printStackTrace();
    Your help is very much appreciated!!!!

  • File Encryption for Mac and Windows

    I need to exchange with Windows users files which will contain financial and other sensitive data. Version Tracker & Mac Update have lots of Mac only encryption programs but I'm looking for one that works on both platforms.

    The ideal solution would be PGP, which would not require you to ever transmit a key that could be intercepted and used to access the data. With PGP, you have a public key and a private key, and your colleague/client has a public key and a private key. You trade public keys, and protect your private keys. When you send data, you encrypt using a public key, and then only someone with the corresponding private key can decrypt it.
    I've never tried this, but there's some free PGP software at:
    http://www.pgpi.org/

  • Executing another program with command line arguments

    I am very new to Java, so bare with me.
    I have written an encryption/decryption program in C (that accepts command line arguments of the key, mode (encrypt/decrypt), and file), and I have written a GUI for it in Java. It accepts the filename (and has a button which opens the "File/Open" dialog), key, and mode, and has a button to Start the process of the encryption. I'd like for that "Start" button to call my encryption program in C (eep.exe) with the command line arguments of the file, key, and mode. This is what I have written so far :
    Start = new JButton("Start");
    Start.setBounds(150, 180, 90, 25);
    Start.addActionListener(new ActionListener() {     
    public void actionPerformed(ActionEvent ae) {
    Desktop.open(new File("C:\\eep.exe" + " " + filename + " " + mode + " " + key));
    However, I get the error "Cannot make a static reference to the non-static method open(File) from the type Desktop" on the Desktop.open command.
    What should I do? Is Desktop.Open the right way to go about this? If not, what is the right way to go about it?
    Thanks in advance.

    That has helped greatly, but I cannot pass command line arguments to it.
    Using :
    try {
        Desktop.getDesktop().open(new File("C:\\eep.exe"));
    catch (Exception e) {
       System.out.println("Error executing.");
    }I can execute eep.exe, but when I try to pass command line arguments to it, such as
    Desktop.getDesktop().open(new File("C:\\eep.exe" + " " + filename));it fails, get caught and prints "Error Executing."
    I have also tried loading the program, as well as some command line arguments into an array of strings :
    String[] cmdArray = {"C:\\eep.exe", filename};
    Desktop.getDesktop().open(new File(cmdArray));But it gives me the error "The constructor File(String[]) is undefined" on the
    new File (cmdArray)part of the command.

  • Custom Encryption

    I created an encryption program that is one-way and I would like to convert it to an algorithm. I have been looking for someone that would like to take this callenge but I can't find anyone. It is simple but powerful. Please help.
    Thank you,
    Andrew Admire

    I would like someone to look at my code and be able to point me in the direction of creating a custom ssl. Like creating a VPN using my encryption. Does that make sense?
    Andrew

  • Call Encryption Software from SAP

    There is an encryption software installed in the user's PC.
    Some files are being downloaded in to the user's PC from SAP using a report.
    Is it possible to call this encryption software in the user's PC to encrypt all the downloaded files from SAP ?

    Hi,
    Yes, there are many ways to call the executable program <br>
    1) Call by OLE <br>
        You can call by OLE technique only if your encryption program provides OLE objects to be exposed for other applications. For example, call Excel or Word OLE objects from ABAP. You can search on SAP for OLE demonstration<br>
    2) Call directly executable program <br>
    You can call executable program in your front end station from your abap source code by using fct. module GUI_RUN . This call works only in foreground since the executable program is in your front end station and you have to know the parameters that your external program can accept (ie. you have to read your encryption manual).If you do not know the parameters to be sent to you encryption program then you coud crate a batch file in Windows and run the batch file from ABAP. <br>
    Example:<br>
    CALL FUNCTION 'GUI_RUN'<br>
      EXPORTING<br>
        COMMAND          = 'NOTEPAD.EXE'<br>
       PARAMETER         = 'c:\TEST.TXT'.<br>
    3) Call by DDE (Data dynamic Exchange)
    This one, I forget how to do this since done about 5 years ago, Return to you later if you really need this technique

  • How to stop the encription program

    The new encryption software Mozilla added with update 10 is terrible. It's paranoid, no way to delete the web sites it collects. I do not like being monitored & even if it's not seen by anyone but me I want it gone! It prevents me from adding a new address to the bar on top since it gets locked up. It stinks, It sucks. How can I delete the sites I've visited & why is it being kept anyway?

    '''Hi John99, Thanks for responding so quickly. the address bar at the top of the page is where you can type in the exact address of an https:// site. ''' Some web pages, including this one. Click on this link pls. & scroll down to read the description of the "blue" highlight words" & what it means.
    https://support.mozilla.org/en-US/kb/Site%20Identity%20Button
    The encryption program is called a "Site Identity Button". It's new since I updated to the v. 10. If you see the blue highlighted page name & left click on it you'll see what I'm talking about. It says this site has been encrypted to prevent eavesdropping. Clicking on the "more information? button brings up various parts of this program. You'll see a list of all the web pages you've gone to, how many times & a lot of other info. I don't need or want this & see possible problems with privacy from the company that is gathering all of my web browsing info. It's not paranoia if what you fear is real. Anyway there's no way to delete this growing list of visited web pages & no way to turn it off that I could find. The biggest frustration is that in order to go to another page I have to close this page & open a new one because the address bar is locked when this encryption thing is "protecting" it. I dislike this feature very much. Different web pages prompt different companies doing the info gathering on a particular page. Why is this needed? NO one else uses my computer. I know first hand, for sure that some emails & social media communications are being monitored by govt. agencies. I have a tracker that gives me reports on any email I choose. It is a fact that if a subject line uses "certain trigger words" it's picked up immediately & diverted to computer systems searching for groups of folks complaining about the govt. or planning anything. This is a fact. So, I don't want anyone, not anyone for any reason monitoring & capturing personal information on web sites I visit. This so called encrypted software stores my passwords, sign in names, times I've visited that page, & a lot of other very personal info. I don't need to store this info so I certainly don't want any encryption program provided by people who aren't known & whose intentions are not clear. Please help me if you can. Thanks. Sandy

  • New App Note explains how to program Xilinx 7 series FPGA's eFUSEs on a device programmer

    Xilinx 7 series devices contain one-time-programmable eFUSEs to hold the encryption key for on-chip AES encryption/decryption as well as a 32-bit, user-defined value that can be used for any application. The new Xilinx App Note XAPP1260, “eFUSE Programming on a Device Programmer,” explains the files you’ll need to program these eFUSE bits and how to use the Xilinx Vivado Design Suite to create an encrypted programming bitstream for use in a device programmer. A link to a reference design is provided as well.
     

    Thanks for that information.
    I did not see that the “go to view link” could change documents. I thought it was only within a document.
    I manually added two “go to view links” and that seems to work on both mac and pc computers.
    That brings up two questions.
    For old files can a acrobat java script batch file be setup to read the hyperlinks in a pdf document  and replace them with a “go to view link” style?
    Can one place a “go to view link” style in a word document and then have the adobe convert to acrobat process it into the pdf format with the rest of the document? (or set up the converter to make word hyperlinks change to pdf “go to view links”?

  • Additional Program embedded in PI server

    Hi Experts,
    I have was thinking about this scenario. A file (unencrypted) send from a sending system, then dump to a file server, picked by PI  then PI will use the sending systems encryption program to encrypt the file then send back to another file directory, then picked up by receiving system.
    Let's put into consideration that we will be using the encryption software from the provided from the sending system and not customize or use another encryption software aside from the one provided.
    Is this possible?
    Cheers,
    R-jay

    hi,
    >>>software to encrypt data and not its impossible to add that existing software and link it to an adapter. Is my understanding correct?
    you can also do that
    if this external software can pull files and descrypt them and return the result then you can use PI to put the file in a correct place and then get the decrypted file from the return folder - so depending on the features which this additional tool provides
    Regards,
    Michal Krawczyk

  • Horizon FLEX 1.1 - Question on Encryption Password

    Hi all,
    For my Horizon FLEX deployment, VMware Workstation 11 is used to create source VM. When the source VM is assigned to multiple users, it seems that the power-on passphrase (encryption password) will be the same for those users. Other than creating multiple source VMs with different encryption password, is there another workaround to achieve a similar result (different power-on passphrase for different users)?
    Any idea, workaround and suggestion are welcome.
    Thanks and regards,
    Tony Yeung

    Hello at the moment the only option is to force the user to change the password after the first logon. Check the entitlement for that setting The tick box under the restrictions.
    Keep in mind that you can upload a template only ones as an image.

  • Encryption in Procedure Builder

    Could anybody tell to me how to encrypt program units in Procedure Builder, like happens with SYS Program Units for every users?

    There is a utlity called wrap.exe you can use it.

Maybe you are looking for

  • Commission Group not picking in sales order

    Hi We have created the Commission Group (ie. 6 ) in product master in R/3 and successfully downloaded in to CRM product master.  When we create the sales order in CRM the relevant commission is not being picked up in the order from the product master

  • Log sql of a specific user

    Hi Is there a way to trace all the sql query of a specific user in Oracle 9i ? I already try logminer but i find it not very flexible. Thanks for answer.

  • How to edit data selection(Date) for an Init Delta Infopackage

    Hi Experts, We have a Process Chain which contains an Delta Infopackage. This Delta Infopackage has a Data Selection (Date) condition which is till 12/2008. As well the same date selection is present in the init method as 12/2008. Also we need to cha

  • Is is possible to get AppStore to scan Mac and import apps currently installed?

    Hi, I have a lot of Apps already installed on my Mac and l noticed that some are already in the App Store. Is is possible to automatically scan my Mac and find any apps that area already in the App Store and then download them? So l don't have to go

  • Help! Ipod 40 gig does not display songs/folders

    My daughter says none of her songs or folders show up on her Ipod. We had this problem 3 mos ago & they replaced her Ipod with a new one. Any Suggestions mon 40 gig   Windows 2000