How to encrypt with a string as input,but not a key object

As far as I know,when encrypt or decrypt ,a key must first be got,and the key is first generate by a tool or from SecurityRandom,that means I can not generate the same key with the same input.Does there is a method which can generate a same with the same input string?
There is a need to transfer file between to site,and the customer wish to encrypt these files during transfering,and they want to store a string into each database at each site,when sending and receiving files,get the string from the database to encrypt or decrypt the file,they alse want to have a control of the string,they can change the string randomly if they wish as long as long keep each string is equal,how to realize this?

I think what you are looking for is a password based encryption (PBE). An example of using the same is mentioned in JCE reference guide. Below is the relevant code/docs from the rference guide.
Using Password-Based Encryption
In this example, we prompt the user for a password from which we derive an encryption key.
It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.
For that reason, the javax.crypto.spec.PBEKeySpec class takes (and returns) a password as a char array.
The following method is an example of how to collect a user password as a char array:
     * Reads user password from given input stream.
    public char[] readPasswd(InputStream in) throws IOException {
        char[] lineBuffer;
        char[] buf;
        int i;
        buf = lineBuffer = new char[128];
        int room = buf.length;
        int offset = 0;
        int c;
loop:   while (true) {
            switch (c = in.read()) {
              case -1:
              case '\n':
                break loop;
              case '\r':
                int c2 = in.read();
                if ((c2 != '\n') && (c2 != -1)) {
                    if (!(in instanceof PushbackInputStream)) {
                        in = new PushbackInputStream(in);
                    ((PushbackInputStream)in).unread(c2);
                } else
                    break loop;
              default:
                if (--room < 0) {
                    buf = new char[offset + 128];
                    room = buf.length - offset - 1;
                    System.arraycopy(lineBuffer, 0, buf, 0, offset);
                    Arrays.fill(lineBuffer, ' ');
                    lineBuffer = buf;
                buf[offset++] = (char) c;
                break;
        if (offset == 0) {
            return null;
        char[] ret = new char[offset];
        System.arraycopy(buf, 0, ret, 0, offset);
        Arrays.fill(buf, ' ');
        return ret;
    }In order to use Password-Based Encryption (PBE) as defined in PKCS #5, we have to specify a salt and an iteration count. The same salt and iteration count that are used for encryption must be used for decryption:
    PBEKeySpec pbeKeySpec;
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Salt
    byte[] salt = {
        (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
        (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
    // Iteration count
    int count = 20;
    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);
    // Prompt user for encryption password.
    // Collect user password as char array (using the
    // "readPasswd" method from above), and convert
    // it into a SecretKey object, using a PBE key
    // factory.
    System.out.print("Enter encryption password:  ");
    System.out.flush();
    pbeKeySpec = new PBEKeySpec(readPasswd(System.in));
    keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
    // Create PBE Cipher
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    // Initialize PBE Cipher with key and parameters
    pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
    // Our cleartext
    byte[] cleartext = "This is another example".getBytes();
    // Encrypt the cleartext
    byte[] ciphertext = pbeCipher.doFinal(cleartext);Hope this helps
Sai Pullabhotla

Similar Messages

  • Hi! I have a library of around 1000 songs on my iTunes, I recently synced my phone and all was lost, my partner has the same songs on hers with a different sign in, but not backed up anywhere, any suggestion on how I can store her tunes in my account ???

    Hi! I have a library of around 1000 songs on my iTunes, I recently synced my phone and all was lost, my partner has the same songs on hers with a different sign in, but not backed up anywhere, any suggestion on how I can store her tunes in my account ??? Then sync them to mine? When I sign her phone into her account I get a message warning that if I sync the dogs on her phone will be replaced by the ones in the library! But as there are no songs there I'm reluctant to continue!!! Please help this non techi guy.!!!!!

    Hello Solid Buck,
    Thank you so much for providing the details about the duplicate song issue you are experiencing.  It sounds like you would like to remove the duplicate songs that will not play on your iPhone, but when you connect it to iTunes, iTunes only shows you one copy of the song on your iPhone. 
    In this situation, I recommend deleting the individual songs that do not play directly from your iPhone.  I found the steps to do this on page 61 of the iPhone User Guide (http://manuals.info.apple.com/en_US/iphone_user_guide.pdf):
    Delete a song from iPhone: In Songs, swipe the song, then tap Delete.
    Thank you for using Apple Support Communities.
    Best,
    Sheila M.

  • I have my iPhone 4s backed up on my mac but it seems it was encrypted with a password which i do not remember is there any other option to retrieve to the backup without restoring the device as a new one. Also I do not have access to a windows system.

    I have my iPhone 4s backed up on my mac but it seems it was encrypted with a password which i do not remember is there any other option to retrieve to the backup without restoring the device as a new one. Also I do not have access to a windows system.

    Sorry no, if you don't knnow the encrypted password, then you can't use that backjup.

  • Hi, I have a Indesign user who inherited a PC with Indesign installed. Indesign works with old PC user profile but not the new user. Any ideas how I can resolve this?

    Hi, I have a Indesign user who inherited a PC with Indesign installed. Indesign works with old PC user profile but not the new user. Any ideas how I can resolve this?

    Question # 1 is what do you mean by "inherited"? Is this a case where the computer belonged to someone else? Your user would not be entitled to use a program licensed to someone else.

  • How can I share my music and some apps with my children's devices, but not share iMessage

    How can I share my music and some apps with my children's devices, but not share iMessage

    Then only set up your account in "Settings > iTunes & App Stores" and don't give them your password .

  • I don't want to sync my new ipod nano with all my music on my mac. i only want to put on certain albums. how do i transfer some of the music but not all? thank you.

    i want to add music to my new ipod nano but i don't want to sync all the music onto the nano from my mac. how do i transfer some of the music but not all? thank you.

    Hello,
      It is 2015 and iTunes still wants to tell me what to listen to. This problem still persists. The only solution I have found is to select "Manual ..." and pick one by one the items to sync.
      When I select items to sync by artist or genre they do copy to the device. Then iTunes continues randomly selecting music until the device is full. When I want to load the Nano for a road trip I don't want 20% of the tracks to be Chakra meditation. When little Nano is docked on the nightstand alarm clock I DON'T want to hear Motorhead, Ministry, etc.
      For all the effort aPple puts into seamless integration and ease of use ... Why the heck is it so hard to say NO? Sync these tracks and NOT those. Stop asking me to log in to your cloud service BTW. I do not want it.
    Thanks,
    Disgruntled Sour aPple User

  • How to apply an InDesign Paragraph Rule above, but not when first in column

    How do I apply a paragraph rule "above" but not when first in a column. In other words, the rule above will only run if it isn't the first paragraph in the column (even if it appears in a multi-column text frame).
    Before you jump the gun: Rule below will not solve that, for various reasons.
    Thanks much in advance.

    Aha! Apparently totally!
    Here a similar way to yours with an anchored block. Copy it and launch this simple regex. Easy with no headache! 

  • How do I delete just the firefox bookmarks but not the the bookmarks toolbar icons

    I deleted my firefox bookmarks so I could import my gooogle bookmarks,but this also deleted my firefox bookmarks toolbar entries...it took me along time to put these in again.
    How do I delete just the firefox bookmarks but not the the bookmarks toolbar icons

    What kind of problems did you get after installing the extension?
    You can try to remove the history manually in the History Manager by doing a search for a colon.
    How many history items do you have to remove?
    If you only want to do this once or occasionally then you can consider to use this code:
    *http://kb.mozillazine.org/User:Dickvl/JavaScript_Error_Console#Expire_History_By_Days
    You will have to calculate the number of days that you want to keep to remove only history items from 2013 and older (365+31+28+26)
    You can open the Browser Console (Firefox/Tools > Web Developer).
    Paste the JavaScript code in the command line and press the Enter key to run the code.
    *Toggle the devtools.chrome.enabled pref on the <b>about:config</b> page to true to enable the command line
    *https://developer.mozilla.org/Tools/Browser_Console#Browser_Console_command_line
    <pre><nowiki>
    (function(){
    /* expire history by days, based upon bug 660646 comment 5/7 - [email protected] */
    var Cc = Components.classes, Ci = Components.interfaces;
    var his = Cc["@mozilla.org/browser/nav-history-service;1"].getService(Ci.nsIBrowserHistory);
    var prs = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
    var day = 0, obj = new Object, txt = "Expire History"; obj.value = "90";
    if (prs.prompt(null,txt,"Days of history to keep",obj,null,{})){
    day = parseInt(obj.value);
    if(!isNaN(day)&&(day>0)){
    his.removeVisitsByTimeframe(0,(new Date().setHours(0,0,0,0) - day * 86400000) * 1000);
    }else{ prs.alert(null,txt,"Error Parsing Days: "+obj.value); }
    </nowiki></pre>
    If hat doesn't work then you may have a problem with the places.sqlite database file and you may have to reset places.sqlite.
    *Places Maintenance: https://addons.mozilla.org/firefox/addon/places-maintenance/
    You can move (copy/paste) history items that you want to keep to a bookmarks folder.
    See also:
    *Norwell History Tools: https://addons.mozilla.org/firefox/addon/norwell/

  • HT4759 account - can someone please tell me the settings to use (port number, encryption etc) as I can receive but not send. Thanks!

    I'm trying to use Outlook to receive and send email from my mail.me.com account - can someone please tell me the settings to use (port number, encryption etc) as I can receive but not send. Thanks!

    Looks like there is a general problem with SMTP mail today. Lots of people posting similar things.

  • I have a 60 inch Sony XBR TV that has DVI input but not HDMI. I am using an adapter to get the video from my Apple TV, but the screen flashes a lot. Do I have any other choices other than buying a new TV?

    I have a 60 inch Sony XBR TV that has DVI input but not HDMI. I am using an adapter to get the video from my Apple TV to the Sony, but the screen flashes a lot. Do I have any other choices other than buying a new TV?

    Is this an iphone question?
    You have posted in the iphone forum.

  • HT4864 How can I delete / close my iCloud email but not my iCloud account

    How can I delete / close my iCloud email but not my iCloud account

    On your iOS device, go to Settings>iCloud and turn Mail off.  On a Mac, go to System Preferences>iCloud and uncheck Mail.

  • How do I update my iPhone 3G firmware but not to the latest version?

    How do I update my iPhone 3G firmware but not to the latest version?
    I currently am running 3.1 but would like to update it to the 4.1 version (not the latest 4.3 version). How do I do this? I have already gone online and downloaded the 4.1 firmware for iPhone 3G but not sure how to install it. I unzipped the file then tried to do the Shift>Update trick but none of the downloaded files could be selected. Am I doing something wrong?

    There is no official way to do what you want, that's why the files can't be selected. iOS 4.2.1 is the last officially signed firmware available for your phone. If you want to install any other firmware you'll have to go elsewhere for instructions as such cannot be discussed here, per this forum's terms of use, sorry.

  • How to track materials shipped by the Vendor but not received

    Hi,
    Can anyone explain how to track materials shipped by the Vendor but not received at the customer plant?
    Thanks in advance

    You can use confirmation control in PO for tracking
    1. OMGZ to Configure Confirmation control.
        Here  you can specify the order in which you expect confirmations from your vendors.
    2. MK02 - to assign Confirmation Control to Vendor in Purchasing View.
    3. To view acknowledgments that have been received,
        in PO choose Item --> Confirmations --> Overview
    Check this out-
    http://www.sap-img.com/materials/explain-about-the-po-confirmation-control-key-in-detail.htm

  • How to use the dll  created by c++ but not write a jni wrapper around

    how to use the dll created by c++ but not write a jni wrapper around through a java program. now I can't access that dll like this directly from java.

    Your question is unclear. (You haven't said what dll you are talking about.)
    But:
    If you are talking about an existing dll, then the only alternative to writing a wrapper is to use one of the wrapper generators floating around. Do a search on JACE.
    If you are talking about a dll you are writing, then run jah and get the interface to match java right away; then you won't have to write a wrapper.

  • How come people usually talk about crucial memory, but not samsung?

    by the way, how come people usually talk about crucial memory, but not samsung?
    they both cl 3.
    I not buying the memory from crucial, but I buying in canadacomputers.ca
    I need to find which ram is compatible within 7 days or else I can't refund.
    pls help

    crucial was the best memory back in the SDram days but in DDR i would say mushkin is the best check the sticky post at the top of this forum compatiable ram that is if your using a K7N2 board

Maybe you are looking for