Safest storage of secret keys

In the process of developing our intranet, we are storing SSN
information as well. Since this is confidential, I want to make
sure I take the best practices in safe-guarding it. So how would
you go about doing it?
I was thinking I could use GenerateSecretKey() and then use
Encrypt with AES, but my problem arises from, "do we store the
generated secret key in the database?) Or is it better to use a
value in the DB we hold on that individual person for a key?
I understand that if I store it in the DB, then additional
security measures include having to close off who gets access to
reading data from database tables, and that's understandable, I'm
just trying to devise the best COLDFUSION-related practices for
storing confidential data.
Cause in the same manner, if someone had access to read CF
page code, they could see something like:
<cfset mySSN = Decrypt( strHashedValue, users.key, "AES" )
/>
And figure out what was being done (so I have to ensure FILE
based security as well, but again, just within the realm of CF,
what's the best thing to do?

Here is how I have done this in the past - but there might be
better methods with CF8.
Yes you have to have a key. It is vulnerable. It should be
stored off the web root in a file (with locked down permissions) or
on a separate database preferably on a separate server. I use a
file. CFinclude (or otherwise externally reference) the key into
your encryption / decryption code. You don't want to hard code the
key into your encryption / decryption routines directly because if
that code somehow gets exposed in an error message (which shouldn't
happen with catch/try but.....) then your key would be exposed.
Make sense?
You are banking on the idea that it is very unlikely,
assuming you have good security practices, that a hacker is going
to crack your DB AND the file you have the key stored in.
No security is perfect.

Similar Messages

  • How to save secret key in the NSS certDB and then retrieve it through Java?

    Hi,
    I 'm pretty new trying to handle keying material for NSS fips mode.
    After following the guidelines from http://java.sun.com/javase/6/docs/technotes/guides/security/p11guide.html#NSS I need my code to use SecretKeyFactory method generateSecret with DESedeKeySpec parameter in the following way:
    Provider nss = new sun.security.pkcs11.SunPKCS11(configFileName);
    Security.addProvider(nss);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede", nss);
    DESedeKeySpec keySpec = new DESedeKeySpec(new String("abcdefghijklmnopqrstuvw").getBytes("UTF-8"));
    SecretKey key = keyFactory.generateSecret(keySpec);
    The question is: what are the steps needed to save secret key "abcdefghijklmnopqrstuvw" in NSS certDB in the fips mode (nssModule = fips in pkcs#11 conf. file) and how should it be retrieved in the Java code?
    Any help will be appreciated...

    OK...I didn't test this in FIPS mode, but it works in keystore mode (which says persistent storage of keys)
    KeyGenerator kg = KeyGenerator.getInstance("DESede",nss);
    kg.init(192);  //yields 168-bit key
    SecretKey tripleDesKey = kg.generateKey();
    KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(tripleDesKey);
    ks.setEntry(randAlias, skEntry, new KeyStore.PasswordProtection(password));I was generating some random bytes and base64'ing them to get a random alias on each execution of the program. I'd also loop through and print out the aliases before I generated another key to ensure it was storing the key in between runs which it was.
    Command-line proof the keys are in db:
    symkeyutil -L -d .
    Enter Password or Pin for "NSS Certificate DB":
         Name            Len Strength     Type    Data
    NSS Certificate DB:
    7i/XoKcaLhU=          24    168         des3  <restricted>
    Yzjt7W+AIgc=          24    168         des3  <restricted>
    RkOTZssCEQM=          24    168         des3  <restricted>
    S2BHRcFUyAA=          24    168         des3  <restricted>
    secretKeyAlias        24    168         des3  <restricted>
    R/DaVy1z1MM=          24    168         des3  <restricted>
    IdpdnIDzOYs=          24    168         des3  <restricted>
    SeVASW8PrOc=          24    168         des3  <restricted>
    c6Ml/9I7thQ=          24    168         des3  <restricted>Edited by: dstutz on May 15, 2008 12:28 PM
    Edit again:
    I changed the mode in the cfg file to fips and used modutil to change module to fips mode and it still works...all the keys I created in keystore mode are still there and I can add new ones.
    C:\nss>symkeyutil -L -d .
    Enter Password or Pin for "NSS FIPS 140-2 Certificate DB":
         Name            Len Strength     Type    Data
    NSS FIPS 140-2 Certificate DB:
    LmsZDBaaCw8=          24    168         des3  <restricted>
    EQaX3wdJ1cY=          24    168         des3  <restricted>
    7i/XoKcaLhU=          24    168         des3  <restricted>
    Yzjt7W+AIgc=          24    168         des3  <restricted>
    RkOTZssCEQM=          24    168         des3  <restricted>
    S2BHRcFUyAA=          24    168         des3  <restricted>
    secretKeyAlias        24    168         des3  <restricted>
    UsY23mwSzEM=          24    168         des3  <restricted>
    B/auMw2OTvE=          24    168         des3  <restricted>
    coqyCAAJpsk=          24    168         des3  <restricted>
    vVBHLg1r3cY=          24    168         des3  <restricted>
    R/DaVy1z1MM=          24    168         des3  <restricted>
    IdpdnIDzOYs=          24    168         des3  <restricted>
    SeVASW8PrOc=          24    168         des3  <restricted>
    c6Ml/9I7thQ=          24    168         des3  <restricted>Edited by: dstutz on May 15, 2008 12:56 PM

  • Accessing blobs in private container without Shared Access Secret key

    Is there any way to access blobs in private blob container without Shared Access Secret key ? i mean any User / Role based security or domain level security i.e only our domain should be able to access blobs in private container etc.
    Actually i don't want to append SAS key after each blob url to access it, i want my container to be private and also i want to access each blob in that container without SAS key
    any way currently available or planned in future release ?

    Hi Yazeem,
    > That main page loads sucessfully but the js, css, xml files which this page accesses are unable to load because SAS key is not appended to their URL automatically.
    If the main page is served by a http handler and the js, css, xml files are linked using relative address, these files will also be served by the http handler too. For example, if the http handler serves a page in address
    http://xxx.cloudapp.net/blobproxy/index.html and the page links to a script file using tag
    <script src="myscript.js"></script>, actually the browser will use address
    http://xxx.cloudapp.net/blobproxy/myscript.js to access the script file. So the solution is to create a http handler to serve all requests to address
    http://xxx.cloudapp.netb/blobproxy/*.
    For test purpose, I made this sample. Please add a class file BlobProxy.cs to your web role project:
    using System;
    using System.Web;
    using Microsoft.WindowsAzure.StorageClient;
    using Microsoft.WindowsAzure;
    namespace WebApplication2
    public class BlobProxy : IHttpHandler
    // Please replace this with your blob container name.
    const string blobContainerName = "files";
    public bool IsReusable
    get { return false; }
    public void ProcessRequest(HttpContext context)
    // Get the file name.
    string fileName = context.Request.Path.Replace("/blobproxy/", string.Empty);
    // Get the blob from blob storage.
    var storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
    var blobStorage = storageAccount.CreateCloudBlobClient();
    string blobAddress = blobContainerName + "/" + fileName;
    CloudBlob blob = blobStorage.GetBlobReference(blobAddress);
    // Read blob content to response.
    context.Response.Clear();
    try
    blob.FetchAttributes();
    context.Response.ContentType = blob.Properties.ContentType;
    blob.DownloadToStream(context.Response.OutputStream);
    catch (Exception ex)
    context.Response.Write(ex.ToString());
    context.Response.End();
    Then please add this http handler to web.config file:
    <configuration>
    <system.webServer>
    <handlers>
    <add name="BlobProxy" verb="*" path="/blobproxy/*" type="WebApplication2.BlobProxy"/>
    </handlers>
    </system.webServer>
    </configuration>
    Before running the project, please replace blobContainerName with your own blob container that contains both html and related files. Then start debugging the Azure service project and then you can use the following address to access the page:
    http://127.0.0.1:[port number]/blobproxy/[page name]
    I above sample does not work for you, please let me know.
    Thanks.
    Wengchao Zeng
    Please mark the replies as answers if they help or unmark if not.
    If you have any feedback about my replies, please contact
    [email protected].
    Microsoft One Code Framework

  • How to  use Shared secret key(diffie hellman) for encryption n decryption

    In my client server program i wanted to encrypt a random key using shared secret key for encryption and decryption with DES. but i'm unable to encrypt it as init() is not takin the shared secret key for encryption. somebody please help. my mail id - [email protected]

    You need to post some code because it works for everyone else.

  • Weblogic.security.internal.encryption.EncryptionServiceException: Error decrypting Secret Key

    Hi all,
    I have one admin server 8 managed servers in cluster environment. I am using node
    manager to start managed servers. I used the demo certificate and private key
    file provided by BEA before getting my real certificate, but when I got the real
    certificate the node manager can't no more. The error I am getting is this :
    <Dec 24, 2002 10:01:27 AM EST> <Info> <NodeManager> <NodeManager: for information
    on command line options, try "java weblogic.nodemanager.NodeManager help">
    <Dec 24, 2002 10:01:27 AM EST> <Info> <NodeManager> <Starting NodeManager >
    Exception in thread "main" weblogic.security.internal.encryption.EncryptionServiceException:
    Error decrypting Secret Key
         at weblogic.security.internal.encryption.JSafeSecretKeyEncryptor.decryptSecretKey(JSafeSecretKeyEncryptor.java:119)
         at weblogic.security.internal.encryption.JSafeEncryptionServiceImpl.<init>(JSafeEncryptionServiceImpl.java:205)
         at weblogic.security.internal.encryption.JSafeEncryptionServiceFactory.getEncryptionService(JSafeEncryptionServiceFactory.java:23)
         at weblogic.nodemanager.NodeManager.initializeEncryptionService(NodeManager.java:727)
         at weblogic.nodemanager.NodeManager.init(NodeManager.java:425)
         at weblogic.nodemanager.NodeManager.main(NodeManager.java:649)
    --------------- nested within: ------------------
    weblogic.security.internal.encryption.EncryptionServiceException - with nested
    exception:
    [weblogic.security.internal.encryption.EncryptionServiceException: Error decrypting
    Secret Key]
         at weblogic.security.internal.encryption.JSafeEncryptionServiceImpl.<init>(JSafeEncryptionServiceImpl.java:226)
         at weblogic.security.internal.encryption.JSafeEncryptionServiceFactory.getEncryptionService(JSafeEncryptionServiceFactory.java:23)
         at weblogic.nodemanager.NodeManager.initializeEncryptionService(NodeManager.java:727)
         at weblogic.nodemanager.NodeManager.init(NodeManager.java:425)
         at weblogic.nodemanager.NodeManager.main(NodeManager.java:649)
    here is the setting of node manager
    # Set user-defined variables.
    BEA_HOME="/opt/app/weblogic"
    WL_HOME=${BEA_HOME}/weblogic700
    NODEMGR_HOME=${BEA_HOME}/common/nodemanager/config
    JAVA_HOME=${BEA_HOME}/software/j2sdk1_3_1_06
    #Set NODEMANAGER variables
    NODEMANAGER_CERTIFICATEFILE=${NODEMGR_HOME}/uxmwpr01_nam_pwcinternal_com-cert.pem
    NODEMANAGER_KEYFILE=${NODEMGR_HOME}/uxmwpr01_nam_pwcinternal_com-key.der
    NODEMANAGER_KEYPASSWORD="wR2DfgiHjF0m4"
    NODEMANAGER_LISTENADDRESS="uxmwpr01"
    NODEMANAGER_LISTENPORT="5501"
    NODEMANAGER_REVERSEDNS="true"
    NODEMANAGER_SSLVERIFICATION="true"
    NODEMANAGER_STARTTEMPLATE=${NODEMGR_HOME}/startManagedWeblogic
    NODEMANAGER_SSLTRUSTED=${WL_HOME}/server/lib/cacerts
    NODEMANAGER_JAVASECURITY=${WL_HOME}/server/lib/weblogic.policy
    NODEMANAGER_TRUSTEDHOSTS=${NODEMGR_HOME}/nodemanager.hosts
    NODEMANAGER_NATIVEIO="true"
    ${JAVA_HOME}/bin/java ${JAVA_VM} ${MEM_ARGS} ${JAVA_OPTIONS} -classpath "${CLASSPATH}"
    -Dbea.home=${BEA_HOME} -Dweblogic.security.SSL.trustedCAKeyStore=${NODEMANAGER_SSLTRUSTED}
    -Djava.security.policy=${NODEMANAGER_JAVASECURITY} -Dweblogic.nodemanager.javaHome=${JAVA_HOME}
    -Dweblogic.ListenAddress=${NODEMANAGER_LISTENADDRESS} -Dweblogic.ListenPort=${NODEMANAGER_LISTENPORT}
    -Dweblogic.nodemanager.certificateFile=${NODEMANAGER_CERTIFICATEFILE} -Dweblogic.nodemanager.keyFile=${NODEMANAGER_KEYFILE}
    -Dweblogic.nodemanager.keyPassword=${NODEMANAGER_KEYPASSWORD} -Dweblogic.nodemanager.reverseDnsEnabled=${NODEMANAGER_REVERSEDNS}
    -Dweblogic.nodemanager.startTemplate=${NODEMANAGER_STARTTEMPLATE} -Dweblogic.nodemanager.sslHostNameVerificationEnabled=${NODEMANAGER_SSLVERIFICATION}
    -Dweblogic.nodemanager.trustedHosts=${NODEMANAGER_TRUSTEDHOSTS} -Dweblogic.nodemanager.nativeVersionEnabled=${NODEMANAGER_NATIVEIO}
    weblogic.nodemanager.NodeManager

    "Jas" <[email protected]> wrote in message news:<3e657be5$[email protected]>...
    Hi,
    I am wondering if anyone has tried creating a domain on a weblogic server by copying
    and pasting an entire domain directory. ie. Copying %bea_home%\config\DomainName
    to the new installation %bea_home%\config\DomainName.
    When I do this I get the following error when starting up the weblogic server:
    "The WebLogic Server did not start up properly. Exception raised:
    weblogic.security.internal.encryption.EncryptionServiceException:Error decrypting
    Secret Key" when loading config.xml
    I assume this is because the weblogic system password is encrypted in the config.xml
    file. Is there anyway I can get around this so I can easily clone weblogic servers?
    Thanks,
    JasJas,
    Yeah the security key is tied to the server, what exactly are you
    trying to accomplish? Do you want seperate domains or servers? Are
    they on different physical servers?
    Also what version of wls? 6 or 7?
    Will try to help you if I can
    Steve

  • Secret key API in an Ajax Adobe AIR app?

    I'm building an AIR app with Ajax using an API that is
    identical to flickr's API, with a shared secret key. The problem is
    that the air installation package contains all the source and I
    don't want to give away my shared secret. Is there any way to hide
    the secret? Can I hide any of the source, or put the key in the
    encrypted local store pre-installation, or somehow include this
    shared secret within the app without giving it away?
    I thought I had it figured out when I included it as a passed
    param in the application descriptor (e.g.
    <content>index.html?key=xxxxxx-secret=xxxxxxx</content>),
    but then I see that even the application descriptor source is
    included in the .air build! Is there anything I can do????
    Thanks very much for any help!

    thanks Jason - yes it does return an authentication token
    after the user authorizes the application. The shared secret is
    really just a way for the server to recognize the program using the
    API. It is used to sign each transaction between the server and the
    client through the API calls. By giving out the shared secret, I
    would be giving anyone access to disguise themselves as our client
    program. So if they do something wrong with it, our key would be
    revoked, and our client program would no longer work.

  • How to create Secret Key.

    Hi,
    Can any one point me, where I can find to create a Secret Key and store it inside the KeyStore ?
    I am trying to use the w3'c encryption / decryption and I want to create a key which can be compatible to TripleDESCBC or rsa-1_5.
    Since I am new to all these, any pointer will be helpful.
    Thanks in advance,
    -Kalpesh.

    Asuming you have a JCE Provider installed that support 3DES, try this:
    import javax.crypto.*;
    SecretKey generateSecretKey ( String alg ) {
      SecretKey sk = null;          
      try {
        KeyGenerator keyGen = KeyGenerator.getInstance(alg);
        keyGen.init(new SecureRandom());
        sk = (SecretKey)keyGen.generateKey();
        return(sk);
      } catch (Exception e) {
        e.printStackTrace();
        return null;
    }Pass in "DESede/CBC" or "3DES/CBC" for 'alg'. You might also want to specify the pading, depending on the Provider you're using. BouncyCastle is a good open-source JCE provider that supports 3DES.
    Note that RSA is a MUCH different beast - you want a key-PAIR- there, neither half of which is a SecretKey.
    Good luck,
    Grant

  • GPG - How to suppress "You need a passphrase to unlock the secret key.."

    Hi,
    I am trying to decrypt a file using gpg decryption command in unix. I am providing the passphrase in the command line. The file gets successfully decrypted but I get the below messages in the command window.
    You need a passphrase to unlock the secret key for
    user: "user" <[email protected]>"
    2048-bit RSA key, ID 123, created 2009-10-27 (main key ID 123)
    gpg: encrypted with 2048-bit RSA key, ID 123, created 2009-10-27
    "[email protected]>"
    I need to suppress all the messages above. I tried using *.sh 2>/dev/null , but this suppress only the 2nd part of the message and I still get the message "You need a passphrase to unlock the secret key ....."
    Can someone please help me in suppressing all the messages above.
    Thanks in advance

    At the top-right of this page, there's a textbox, with the words "Search Forum" over it and "Go>" to its right. Type the wordssave key to disk into it.
    After doing so, it took me 2m30s to to find the following link on the second page of results:
    http://forum.java.sun.com/thread.jsp?forum=9&thread=283282
    I probably should have looked for a better one - I made a couple of mistakes responding to this one last year, so it's a little embarassing. But it does answer your question.
    "Search" - it's very much your friend...
    Good luck,
    Grant

  • Secret key cipher for two different Java versions

    Hello All.
    I am trying to make a class that uses secret key encryption/decryption for both v1.18 and v1.3.1. That is the same class needs to be useable on both versions. Is this possible? v1.18 does not recoginize any javax.crypto.*. I was able to get the cipher working the way I wanted in just v1.3.1, but not v1.18.
    Any suggestions would be very appreciated.
    No upgrade at this time is possible.
    Thank you in advance,
    Jen

    You can use BouncyCastle JCE.
    http://www.bouncycastle.org/latest_releases.html
    Add the good jar file corresponding to JDK version,
    and you'll be able to use the same code.

  • Wldeploy: EncryptionServiceException, Error decrypting Secret Key

    I am seeing the following error using the ant deploy task in ASCORE_MAIN_LINUX_090629.1800
    weblogic.security.internal.encryption.EncryptionServiceException: weblogic.security.internal.encryption.EncryptionServiceException: weblogic.security.internal.encryption.EncryptionServiceException: [Security:090219]Error decrypting Secret Key com.rsa.jsafe.JSAFE_InputException: Invalid input length for decryption. Should be a multiple of the block size - 8.
    I am [attaching the entire stack|http://webcenter.us.oracle.com/webcenter/content/conn/UCM/path/PersonalSpaces/[email protected]/Public/Stack.txt] and the files [myuserconfigfile.secure|http://webcenter.us.oracle.com/webcenter/content/conn/UCM/path/PersonalSpaces/[email protected]/Public/myuserconfigfile.secure] and [myuserkeyfile.secure|http://webcenter.us.oracle.com/webcenter/content/conn/UCM/path/PersonalSpaces/[email protected]/Public/myuserkeyfile.secure]
    wlst cmd
    storeUserConfig('/scratch/sfrankli/extSpaces/myuserconfigfile.secure', '/scratch/sfrankli/extSpaces/myuserkeyfile.secure')
    has been used to create myuserconfigfile.secure and myuserkeyfile.secure
    the complete stack also contains a
    [wldeploy] Version mismatch between key and supported version; will try to continue
    before it throws the EncryptionServiceException.
    Any ideas what may be going wrong.
    Thanks,
    Sunil.

    Yes we realize that we should not be using the simulator; however the customer needs to get some test transactions sent to the authorizer before a certification blackout.
    We identified the issue as a problem between the POS client and POS server where the new v13.3 password phrase for the simulator did not match. We updated the values to match in the application.properties file and it resolved the problem.
    Thank you for your input though.

  • Secret Key

    hi
    friends
    i amdeveloping internet based application .
    i want to Encrypt the data using Secret key .but what is maxi size of data transfer of that key.
    any hint about encrypting the data.?
    or any better method for fast encryption method tell me ?
    thanks

    The size of the data block that you can encrypt depends on the size of the encryption key and the nature of the encryption algorithm.
    A block cypher such as RSA will only allow you to encrypt a block of data. A streaming cypher such as RC4 will encrypt as much data as you need, using (iirc) a passphrase that is cycled in order to encrypt the data. Obviously the longer the passphrase the better the security of the stream cypher.
    I suggest you read the javax.crypto API documentation.
    McF

  • Secret key for the OpenPGP?????

    What am I getting the message "enter passphrase to unlock the secret key for the OpenPGP certificate:..."  when I try to send email via AOL on my Mac?  My gmail account is fine.  I can't send email via my AOL account from my computer any longer because it is requiring a passphrase which I do not have nor ever set up.  My gmail account is fine.  Help!

    Uninstall GPGTools by following the developer's instructions.
    How can I uninstall your software? / FAQ / Knowledge Base - GPGTools Support

  • Different secret keys with 192 and 256 length

    Hello everybody
    I have this problem.
    I want to generate secret key from my password. I used this code:
    String algorithm = "PBEWITHSHA1AND192BITAES-CBC-BC";
        int iterations = 3456;
        byte [] salt = Hex.decode("20CB84A0CE6F4C5B");
        String pass = "321TestovacieHeslo";
        byte [] passBytes = pass.getBytes("UTF-16BE");
        //1.way
        PKCS12ParametersGenerator gen = new PKCS12ParametersGenerator(new SHA1Digest());
        byte [] testBytes = PKCS5S2ParametersGenerator.PKCS12PasswordToBytes(pass.toCharArray());
        gen.init(testBytes,salt,iterations);
        //gen2.init(testBytes,salt,iterations);
        KeyParameter parameter =
            (KeyParameter)gen.generateDerivedParameters(192);
        //2.way
        SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm);
        SecretKey key = keyFact.generateSecret(
                new PBEKeySpec(pass.toCharArray(), salt, iterations, 192));
        //print
        byte [] output = key.getEncoded();
        byte [] output2 = parameter.getKey(); Both ways give me same results, but now I wanted to achieve same password as from Crypto++.
    This code give same result with 128 bit keys but not with 192 ot 256 bit. (I tried 8/16/24 byte salts)
    Where is problem ? Padding ? Because when I used all same parameter with 128 and 192 bit I got these results:
    128bit:7b4b7b59b230003f452fa4fe7c0eb9c1
    192bit:7b4b7b59b230003f452fa4fe7c0eb9c19231f5a471741535
    My concret case:
    input: password: "321TestovacieHeslo"
    salt:"20CB84A0CE6F4C5B"
    iter:3456
    And I need this 24 byte larger key from Crypto++:
    C6408B48D17A1A38F51AC7F05DE24CBB967049DF9FDDCB8F
    but I got this:
    1eb4b95846cdfb60eae519c8efa2569011e30e964be7cfbd
    Can anybody help me ?
    Thanks

    Have you tried using "ntp update-calendar"?

  • Import/export secret key

    Hello i have a simple program that crypt a string, and i want to
    to know how i can export the secret key.
    My idea is to save a secret string in a file and pass it to the program
    that decrypt the string is it possible ???
    thank
    --sxr                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    OK. First - PLEASE learn how to use the [ code ] tags when posting samples. I didn't even realize you'd posted two classes until I tried to paste 'em into Eclipse.
    Second - you're...confused. Crypting and Decrypt need to share two things: the ciphertext, and the KEY. The key is not available from the AlgorithmParameters. In Decrypt, you're creating a new key from your ciphertext (?!?)
    Since I had a little spare time, I refactored your code somewhat. The only reason to use AlgorithmParameters is to pass in an InitialValue (IV), which CBC-mode needs. The IV is not sensitive data - it's OK to make it public.
    So I just stuck the same IV into both files. You can extend the concept and store the IV as well, if you like.
    The following classes work:import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.IvParameterSpec;
    public class Crypting {
        private static String Password = "sunray";
        public static void main(String[] argvs) throws Exception {
            // Choose an Initial Value (IV)
            byte[] iv = {
                (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04,
                (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08,
            IvParameterSpec ivps = new IvParameterSpec(iv);
            File keyFile = new File("key.txt"); // File that will hold the SecretKey
            File cryptFile = new File("algo.txt"); // File that will hold the ciphertext
            // Creazione del generatore di chiave
            KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
            SecretKey skey = kgen.generateKey();
            // Creazione della chiave
            byte[] rawKey = skey.getEncoded();
            // Encrypt our data
            Cipher cipher = Cipher.getInstance("BLOWFISH/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey, ivps);
            byte[] encrypted = cipher.doFinal(Password.getBytes("UTF8"));
            // Store the KEY
            try {
                DataOutputStream out = new DataOutputStream(new FileOutputStream(keyFile));
                out.write(rawKey, 0, rawKey.length);
                out.close();
            } catch (Throwable e) {
                System.err.println(e);
            // Store the ENCRYPTED DATA
            try {
                DataOutputStream out2 = new DataOutputStream(new FileOutputStream(cryptFile));
                out2.write(encrypted, 0, encrypted.length);
                out2.close();
            } catch (Throwable e) {
                System.err.println(e);
        } // main()
    } //Crypting
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    public class Decrypting {
        public static void main(String[] argv) throws Exception {
            // Choose an Initial Value (IV)
            byte[] iv = {
                (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04,
                (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08,
            IvParameterSpec ivps = new IvParameterSpec(iv);
            File keyFile = new File("key.txt"); // Where's the key?
            File cryptFile = new File("algo.txt"); // Where's the data?
            byte[] ciphertext = null; //ciphertext
            byte[] rawKey = null; // key data
            // Read the KEY BYTES
            try {
                DataInputStream in = new DataInputStream(new FileInputStream(keyFile));
                rawKey = new byte[(int)keyFile.length()];
                in.readFully(rawKey);
                in.close();
            } catch (FileNotFoundException e) {
                System.err.println(e);
            // Read the ENCRYPTED DATA
            try {
                DataInputStream in2 = new DataInputStream(new FileInputStream(cryptFile));
                ciphertext = new byte[(int)cryptFile.length()];
                in2.readFully(ciphertext);
                in2.close();
            } catch (FileNotFoundException e) {
                System.err.println(e);
            //make a key object
            SecretKeySpec key = new SecretKeySpec(rawKey, "Blowfish");
            //make a cipher object
            Cipher cipher = Cipher.getInstance("BLOWFISH/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, ivps);
            // Decrypt the DATA with the KEY
            byte[] original = cipher.doFinal(ciphertext);
            // Spit out the decrypted data
            String originalString = new String(original, "UTF8");
            System.out.println("\nPassword: " + originalString);
        } // main()
    } // DEcrypt classYou really need to do some reading on how crypto works, if you mean to get past this point.
    Good luck,
    Grant

  • Encrypting secret key twice

    Hi.
    I would like to exchange a secret key between two parties (client, server).
    Each has the other's public key certificate, and his own private key.
    I do the following:
    1) Server generates session (symmetric) key.
    2) Server encrypts session key with own private key.
    3) Server encrypts output of (2) with client's public key.
    Client should do the cryptographic opposite, and from thereon, shared session key is used to encrypt data.
    My problem is that I am getting the following:
    javax.crypto.IllegalBlockSizeException "Data must not be longer than 117 bytes"
    I don't want to use Diffie-Helman (otherwise keyAgreement would have done just fine).
    I've tried using Cipher.wrap, SealedObject. Same problem.
    Your help would be appreciated.
    Thanks,
    Yaron Rosenbaum

    I would like to exchange a secret key between two parties (client, server).
    Each has the other's public key certificate, and his own private key.
    I do the following:
    1) Server generates session (symmetric) key.OK.
    2) Server encrypts session key with own private key.That doesn't make sense, unless you mean the server signs the session key with its own private key.
    But why sign the session key?
    3) Server encrypts output of (2) with client's public key.
    Client should do the cryptographic opposite, and from
    thereon, shared session key is used to encrypt data.
    My problem is that I am getting the following:
    javax.crypto.IllegalBlockSizeException "Data must not be longer than 117 bytes"
    That is what I would expect. In general, even with no padding, you cannot guarantee unique decryption
    if the first modulus is greater than the second.

Maybe you are looking for

  • Female to female mini-displayport cable or adapter anyone?

    All that fuss about mini displayport to mini dvi adapter and even to micro dvi for the MBAs - let's face it, its not gonna happen people. Jobs has made it pretty clear about that, so lets stop hoping. Instead lets look forward, and now since mini dis

  • GUI Programming with ABAP - Chapter 9

    I am working my way through the ABAP Objects  (Keller/Krueger) book, doing all the exercises, re-entering all the programs for learning purposes.  I get to Chapter 9, and the package I am working with has moved form Z_ABAP_BOOK to SABAPDEMOS.  There

  • In infopackges Delta Load option is missing.

    Hi All,                For one infopackges initially we were using  "Initialzation Delta  Process " Option in update .       Now we want to change that option into "Delta Load". I went to corrsponding infopackage,but that "Delta load" option itself i

  • Storage Capacity iTunes U

    Hello, There's been one other discussion about this but it's from 2007 and it's been archived so i thought i'd ask again. My school is considering several different ways of publishing course materials on the web and of course iTunes U is something th

  • Why won't the spell checker learn?

    Several times now I've spell checked Numbers documents and told the checker to "learn" unknown words, only to have the same words marked as misspelled or unknown the next time I open the document. Is there some Numbers or system setting that is preve