Cryptography with SAPCRYPTOLIB

Hi Folks,
Anyone have experience with SAPCRYPTOLIB?
The point is, my client have a XI that receives messages via HTTPS from a Web Service. The XML payload has some elements encrypted and I want unencrypted!!!
Anyone knows how to work with this library?
Thanks in advance,
Ricardo.

Hi James,
Forget the XI, the idea is: My client receive messages in XML format, some of the fields are encrypted with algorithm Triple-DES. This information is stored into a Z table of a SAP ERP 2005. The idea is develop an ABAP report that reads this table and decrypt the encrypted fields.
I know that algorithm Triple-DES is a symmetric algorithm and the same key is used to encrypt and decrypt. All information that I read in SAP help about SSF programming is about public key technology… I think that I don’t need to implement the Public Key Infrastructure, but only a simple private key infrastructure.
I would like to use SSF programming to develop this report and I just read the SSF programming guide. I don’t know if I need to use all the functions that it has because the encryption process is already done (the infrastructure is also defined) and all I need to do is the inverse process (decrypt).
I have some questions:
In which place is safe to save the private key? On a table, file, into WAS?
Which extra configurations I need to do to start my ABAP report?
Which functions of a SSFG function group I need to use? Like I said before I think that I only need to decrypt the encrypted data, so it means only a SSF_DEVELOPE function is necessary?
Thanks a lot for your help.
Regards,
Ricardo.

Similar Messages

  • RSA cryptography with NOPAD

    Can anyone provide me with pseudo code/algorithm, that will give the steps to encrypt and decrypt a message using the RSA/NOPAD combination. I will implement using cryptix 3.2.
    If any documentation is available regarding RSA/NOPAD, please provide the link(s) or mail it to my id.
    I also need verified test data to test the implementation. I looked in rsalabs but was unable to find any.
    Thanks to all.
    Regards.
    Arnab.

    sabre150 >Of course there are! The mathematics says that if your planetext converted to number is bigger than the modulus then you will loose information.
    Arnab> Missed this point before. Thank you.
    sabre150 >Also, if your planetext converted to a number is small such that m^e is less than the modulus ............... published by Wiley.
    Arnab> Thanks again.
    sabre150 >I don't understand what you are trying to do? If you are doing it all yourself (as you imply) then YOU will have to split the planetext into blocks and YOU will have to provide any padding.
    Arnab>I am splitting the plain text to proper block, based on the key length. For PKCS#1 implementation I am providing a 11 byte header and padding if necessary.
    For NoPad, I guess I can leave the byte and header out, and just split the message into blocks of size equal to modulus.
    If by "doing it all yourself ", you mean that "am I writing the code to do the splitting and padding" then yes.
    sabre150 >Your search does not seem to have been very thorough because the fifth entry that Google came up with is.......
    Arnab> Thank you for the link. However the test vectors contain data for RSAES-OAEP and RSA-PSS algorithms.
    Cipher text generated using RSAES-PKCS1 or NOPAD obviously will not validate against the test data which are meant for RSAES-OAEP.
    Did I miss anything here?
    Thank you again for your patience and time. Please let me know if you see that I am wrong somewhere.
    Regards.
    Arnab.

  • Cryptography with J2ME / J2EE

    cheers to you all,
    i have to develop an application in which there is encrypted message exchange between a client (Mobile phone) and a server.
    i wil use AES , RSA, HMAC-SHA (for digest) and i don't know where can i find the convenient sources / API since i will use J2ME for the client and J2EE for the server
    help me please
    thanks

    Hi!
    I have to connect an J2ME client to the J2EE server
    and I want to know if is it possible using JNDI/LDAP.
    but I want to realize the connection using JNDI/LDAP.Sounds like you've misunderstood what JNDI/LDAP is.
    You should read up what these two technologies are (and what they are for).
    For what particular reason did you 'want to realize the connection using JNDI/LDAP'?

  • It's possible to sign a PDF file with ABAP????

    Hi all.
    I'm trying to sign PDF file with SAPCRYPTOLIB. I'm 4.7 sap version.
    It's possible to do this?????....
    My question is because I've done all steps to sign a pdf, without errors, and the pdf generated is not signed.
    Can anybody to say me if it's possible to sign a pdf file with ABAP???
    thanks a lot.
    ISmael

    Here: [SAP Interactive Forms by Adobe|SAP Interactive Forms by Adobe;
    Also, please read the forum rules of engagement, it explains to use the forums.

  • How to sign the data with DHPrivateKey

    I am testing DH key exchange protocol. When I run the following code, it works.
    import java.io.*;
    import java.math.BigInteger;
    public class DH2 {
        private DH2() {}
        public static void main(String argv[]) {
            try {
                String mode = "USE_SKIP_DH_PARAMS";
                DH2 keyAgree = new DH2();
                if (argv.length > 1) {
                    keyAgree.usage();
                    throw new Exception("Wrong number of command options");
                } else if (argv.length == 1) {
                    if (!(argv[0].equals("-gen"))) {
                        keyAgree.usage();
                        throw new Exception("Unrecognized flag: " + argv[0]);
                    mode = "GENERATE_DH_PARAMS";
                keyAgree.run(mode);
            } catch (Exception e) {
                System.err.println("Error: " + e);
                System.exit(1);
        private void run(String mode) throws Exception {
            DHParameterSpec dhSkipParamSpec;
            if (mode.equals("GENERATE_DH_PARAMS")) {
                // Some central authority creates new DH parameters
                System.out.println
                    ("Creating Diffie-Hellman parameters (takes VERY long) ...");
                AlgorithmParameterGenerator paramGen
                    = AlgorithmParameterGenerator.getInstance("DH");
                paramGen.init(512);
                AlgorithmParameters params = paramGen.generateParameters();
                dhSkipParamSpec = (DHParameterSpec)params.getParameterSpec
                    (DHParameterSpec.class);
            } else {
                // use some pre-generated, default DH parameters
                System.out.println("Using SKIP Diffie-Hellman parameters");
                dhSkipParamSpec = new DHParameterSpec(skip1024Modulus,
                                                      skip1024Base);
            System.out.println("ALICE: Generate DH keypair ...");
            KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
            aliceKpairGen.initialize(dhSkipParamSpec);
            KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
            System.out.println("ALICE: Initialization ...");
            KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
            aliceKeyAgree.init(aliceKpair.getPrivate());
            byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();
            KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec
                (alicePubKeyEnc);
            PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);
            DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
            System.out.println("BOB: Generate DH keypair ...");
            KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
            bobKpairGen.initialize(dhParamSpec);
            KeyPair bobKpair = bobKpairGen.generateKeyPair();
            System.out.println("BOB: Initialization ...");
            KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
            bobKeyAgree.init(bobKpair.getPrivate());
            byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();
            KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
            x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
            PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
            System.out.println("ALICE: Execute PHASE1 ...");
            aliceKeyAgree.doPhase(bobPubKey, true);
            System.out.println("BOB: Execute PHASE1 ...");
            bobKeyAgree.doPhase(alicePubKey, true);
            byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
            int aliceLen = aliceSharedSecret.length;
            byte[] bobSharedSecret = new byte[aliceLen];
            int bobLen;
            try {
                bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1);
            } catch (ShortBufferException e) {
                System.out.println(e.getMessage());
            bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0);
            System.out.println("Alice secret: " +
              toHexString(aliceSharedSecret));
            System.out.println("Bob secret: " +
              toHexString(bobSharedSecret));
            if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
                throw new Exception("Shared secrets differ");
            System.out.println("Shared secrets are the same");
            System.out.println("Return shared secret as SecretKey object ...");
            bobKeyAgree.doPhase(alicePubKey, true);
            SecretKey bobDesKey = bobKeyAgree.generateSecret("DES");
            aliceKeyAgree.doPhase(bobPubKey, true);
            SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES");
            Cipher bobCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);
            byte[] cleartext = "This is just an example".getBytes();
    //        Signature signature = Signature.getInstance("SHA1withDSA");
    //        signature.initSign(bobKpair.getPrivate());
    //        signature.update(cleartext);
    //        byte[] data = signature.sign();
            byte[] ciphertext = bobCipher.doFinal(cleartext);
            Cipher aliceCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey);
            byte[] recovered = aliceCipher.doFinal(ciphertext);
            if (!java.util.Arrays.equals(cleartext, recovered))
                throw new Exception("DES in CBC mode recovered text is " +
                  "different from cleartext");
            System.out.println("DES in ECB mode recovered text is " +
                "same as cleartext");
            bobCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);
            cleartext = "This is just an example".getBytes();
            ciphertext = bobCipher.doFinal(cleartext);
            byte[] encodedParams = bobCipher.getParameters().getEncoded();
            AlgorithmParameters params = AlgorithmParameters.getInstance("DES");
            params.init(encodedParams);
            aliceCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey, params);
            recovered = aliceCipher.doFinal(ciphertext);
            if (!java.util.Arrays.equals(cleartext, recovered))
                throw new Exception("DES in CBC mode recovered text is " +
                  "different from cleartext");
            System.out.println("DES in CBC mode recovered text is " +
                "same as cleartext");
    }I want to sign the data with Signature,So i add the following code to the sample.
            byte[] cleartext = "This is just an example".getBytes();
         Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initSign(bobKpair.getPrivate());
            signature.update(cleartext);
            byte[] data = signature.sign();
            byte[] ciphertext = bobCipher.doFinal(cleartext);Run the code again, the output is
    Error: java.security.InvalidKeyException: No installed provider supports this key: com.sun.crypto.provider.DHPrivateKey
    What's wrong with the code, It seems that the bob's private key is not instance of DSAPrivateKey but DHPrivateKey.
    what's your comment? thanks a lot.

    slamdunkming wrote:
    thank sabre150 for your reply. But the key pair is generated when I use DH to exchange the secret key. Yes! It is a DH key pair and cannot be used for signing. The DH key pair can only be used for secret sharing.
    If I can not use this private key to sign the data, what can i do?Do I have to generate another key pair for signature? In that way, I will have two key pair. Yep. You can generate a DSA or an RSA key pair to be used for signing.
    Because I use http protocol to exchange the key to get the shared secret key, Yep.
    If I generate another key pair, how can i send the public key to server? Since public keys are 'public' then you can send them in the open to anyone you like. In fact, if you don't publish your public keys then they are pretty much a waste of time. The biggest problem one has with public key is proving 'ownership' - if someone sends me a public key how do I know that the sender is actually who they say they are?.
    I am confused.Some reading might help. A pretty good starting point is "Beginning Cryptography with Java" by David Hook published by Wrox.

  • SNC via SAPCRYPTOLIB

    How to configure SNC with sapcryptolib?? I try to find manual. Can somebody help me to find Administrator Guide or something close?

    Hi Alexey,
    The SNC manual is available from the help portal here:
    http://help.sap.com/saphelp_nw2004s/helpdata/en/db/1f1740198d8f5ce10000000a155106/frameset.htm
    Regards,
    Yonko

  • Performance Impact When Using SNC Communication

    Hello,
    Does anybody know if and how much performance impact there is if we use SNC for communication between the SAP Server and SAPGUI?
    I think there are two areas that may be impacted; Network and server CPU.
    For network load, I did find a part in "Front-End Network Requirements for SAP Business Solutions" document saying "overhead of roughly 350 bytes per user interaction step" but it does not specify the type of encryption.  I wonder if there is any other info on this?
    For CPU impact, how much overhead should I consider for sapgui access?
    I see no field for this in the quicksizer and I can't seem to find any white papers on this subject.
    Thank you in advance.

    >
    Peter Adams wrote:
    > Ken,
    >
    > if you plan to use SAPcryptlib for SNC between SAP servers, then you should use a SAPcryptolib-compatible solution for the SNC communication between SAPGUI and SAP server, and there is only one vendor who can provide this. Let me know, if you need help finding it. My contact information is in my SDN business card.
    Just so Kan is clear - It is not legal to use the SAP cryptolib provided by SAP for SNC between SAP GUI and SAP servers, so if x.509 is the desired mechanism you need to purchase additional software from the company which Peter works for to provide SAP GUI SNC-based SSO. I think instead, Kan might be using the free SAP supplied SNC Kerberos library, which is why I asked him to confirm this in my last post. I doubt he is interested to buy any third party software.
    > As to the performance discussion: first of all, yes, there will be a small performance impact if SNC is used (no matter which type or implementation), but from our experience with many actual SNC implementations, I can state that this is practically not relevant. It is not noticeable by users. There were never any performance discussions with customers. See also SAP Note 1043694.
    I agree with this - the performance impact is not noticed by users, but the system managers who look after the servers where SAP is installed, and the team responsible for the network need to be aware of any differences (if any) when SNC is turned on and when SNC is turned off. I think this is why Kan is asking these questions, not because he is concerned about users noticing any difference when they logon to SAP.
    > Just a first quick comment on certain statements above: Tim's arguments for proving his overall statement are not conclusive from my perspective. Nor do I think his overall statement itself is correct.
    The facts I mentioned are well known facts, e.g. symmetric crypto is far better from performance point of view than asymmetric. I know the examples I have shown which I found when doing a quick google search were not conclusive, but they were shown as initial examples, not necessarily the best examples. This is why I specifically mentioned that if you search in google yourself you will see many more references where comparisons are done between Kerberos (e.g. symmatric) compared with PKI (e.g. asymmetric).
    > First of all, he only selects one aspect of performance - CPU impact of encryption algorithms.
    No, I didn't. Some of the examples I referred to also discuss other differences. I also mentioend other differences such as memory and what protection level is used when configuring SNC.
    > But for a true comparison, you'd have to look at all relevant aspects (latency, network overhead, ...).
    Yes, I agree. No doubts here.
    >Network performance overhead is usuallly worse with Kerberos than with PKI.
    This is not true. When SAP is using SNC, the GSS-API standard is used and so the only network communication involves SAP software sending a standard GSS token from the workstation to the SAP server, and this GSS token is often about the same size, regardless of which mechanism is used, so any network performance differences are not related to the mechanism, but more related to the complexity of the cryptography used on each end (mostly on the server side).
    >Second, you need to look at the specific usage scenario. For example, the first report referenced by Tim is an analysis about different Token Profile mechanism for WS Security, for one specific implementation. This does not allow to draw any conclusion for the SNC use case in general, and for sure not for a specific implemenation. It does not take the overhead for the encryption of the message content into account. Third, Tim associates PKI exclusively with asymmetric encryption. Yes, it is well known that asymmetric algorithms are slower than symmetric ones, but it is also well known that the encryption of the message content (by far the majority of the data) happens with symmetric encryption algorithms in the PKI scenario. With PKI-based SNC, you can even select a symmetric algorithm and use a more performant one that the ones that Kerberos prescribes.
    Kerberos works with many different symmetric algorithms as well, so mentioning that the alg is selectable is not relavent to any comparison.
    > To summarize, I will try and collect facts that will support the opposite point of view. From our practical experience, the performance overhead is not relevant, and criteria like consistency with SAPcryptolib, strength of security, ease of administration, choice of authentication and encryption mechanism, etc. are much more important.
    >
    > Peter

  • I want to understand how crypto works.

    Hi, I want to understand how crypto works and all. where i can start with. i really dont know anything about crypto. i need to understand how DC and keys and algorithims work together and how they work. pls suggest me where and with what i can start.

    Since you asked on the Java Cryptography forum, I would recommend beginning with this book:
    Beginning Cryptography with Java
    David Hook
    ISBN: 978-0-7645-9633-9
    http://www.wrox.com/WileyCDA/WroxTitle/productCd-0764596330.html

  • Why bad padding exception???

    hi guys
    here i am trying to decrypt the already encrypted string by one different encrpytion algo.
    in the example i have encrypted the string by des and then i tried to decrypt it using blowfish but it gives as the output null instead of a random string...because of a bad padding exception(check line 86). help to remove the exception.
    if we try to decrypt the des encrypted string by des again it give n padding exception. why with blowfish???
    // CIPHER / GENERATORS
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.KeyGenerator;
    // KEY SPECIFICATIONS
    import java.security.spec.KeySpec;
    import java.security.spec.AlgorithmParameterSpec;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.PBEParameterSpec;
    // EXCEPTIONS
    import java.security.InvalidAlgorithmParameterException;
    import java.security.NoSuchAlgorithmException;
    import java.security.InvalidKeyException;
    import java.security.spec.InvalidKeySpecException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import java.io.UnsupportedEncodingException;
    import java.io.IOException;
    public class StringEncrypter {
    Cipher ecipher;
    Cipher dcipher;
    StringEncrypter(SecretKey key, String algorithm) {
    try {
    ecipher = Cipher.getInstance(algorithm);
    dcipher = Cipher.getInstance(algorithm);
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    dcipher.init(Cipher.DECRYPT_MODE, key);
    } catch (NoSuchPaddingException e) {
    System.out.println("EXCEPTION: NoSuchPaddingException");
    } catch (NoSuchAlgorithmException e) {
    System.out.println("EXCEPTION: NoSuchAlgorithmException");
    } catch (InvalidKeyException e) {
    System.out.println("EXCEPTION: InvalidKeyException");
    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 (BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (IOException e) {
    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 (BadPaddingException e) {
    System.out.println("BAd padding excception");
    } catch (IllegalBlockSizeException e) {
    System.out.println("IllegalBlockSizeException");
    } catch (UnsupportedEncodingException e) {
    System.out.println("UnsupportedEncodingException");
    } catch (IOException e) {
    System.out.println("IOException");
    return null;
    public static void testUsingSecretKey() {
    try {
              String secretString = "code cant be decrypted!";
              SecretKey desKey = KeyGenerator.getInstance("DES").generateKey();
              SecretKey blowfishKey = KeyGenerator.getInstance("Blowfish").generateKey();
         StringEncrypter desEncrypter = new StringEncrypter(desKey, desKey.getAlgorithm());
              StringEncrypter blowfishEncrypter = new StringEncrypter(blowfishKey, blowfishKey.getAlgorithm());
              String desEncrypted = desEncrypter.encrypt(secretString);     
         String desDecrypted = desEncrypter.decrypt(desEncrypted);
         String blowfishDecrypted = blowfishEncrypter.decrypt(desEncrypted);      
         System.out.println(desKey.getAlgorithm() + " Encryption algorithm");
         System.out.println(" Original String : " + secretString);
         System.out.println(" Encrypted String : " + desEncrypted);
         System.out.println(" Decrypted String : " + desDecrypted);
         System.out.println();
         System.out.println(blowfishKey.getAlgorithm() + " Encryption algorithm");
         System.out.println(" Original String : " + desEncrypted);
         System.out.println(" Decrypted String : " + blowfishDecrypted);
         System.out.println();
         } catch (NoSuchAlgorithmException e) {
         public static void main(String[] args) {
         testUsingSecretKey();
    }

    peter_crypt wrote:
    you are right but this is my question. why cant we do that?? it should be possible.by the way i am working on a project for cryptanalysis . there i need to implement it.You need to spend more time studying and less time programming -
    1) Applied Cryptography, Schneier, Wiley, ISBN 0-471-11709-9
    2) Practical Cryptography, Ferguson and Schneier, Wiley, ISBN 0-471-22357-3
    3) Java Cryptography, Knudsen, O'Reilly, ISBN 1-56592-402-9 dated but still a good starting point
    4) Beginning Cryptography with Java, written by David Hook and published by WROX .

  • How to apply RSA and MD5 on my data?

    Hello everyone...I am a college Student and I have a project two clients connected with server one of them by socket and another by RMI
    and I have been asked to apply CIA (confidentiality, integrity, availability) I know algorithms of cryptograpghy and authnication but I need a hint
    how to use these algorithms ...if there is a class to do this or a simple lesson how to encrypt and decrypt (code) I will be thankfull
    Best regards

    One of the most useful books you will find on the subject of Java cryptography is David Hook's "Beginning Cryptography with Java" (WROX). I would recommend you borrow this from your school/public library or buy it and study it; it will be one of the better investments you will make in your education, Gary Wolf. Good luck.

  • How to encrypt the media data which obtained from JMF?

    hi ,everybody,
    I am a new here, and my group is busy at SIP phone program,and we hava got some problems several days ago.
    we created the DataSource by processor,and we want to encrypt the data before send them out,is there anyone can tell me what should we do?
    please help.
    thanks.

    There are lots and lots of traps you can fall into when talking about encryption of data. I don't have a clue what a SIP phone is but assuming that your program is Java based then you need to do a lot of background reading. A good starting point is "Beginning Cryptography with Java" by David Hook published by Wrox.

  • How can I sign and encrypt massage to send via rmi ??

    Hi,,,
    I want to sign a massage with RMI client private key and then encrypt the message with the signature using the RMI server public key.
    How can I do this ?

    I suspect you won't like my answer but a good starting point is "Beginning Cryptography with Java" by David Hook published by Wrox.
    P.S. It is much more secure to use RMI with secure sockets since this provides both authentication and encryption and most of the work is done by existing system libraries.

  • Help please: Encrypt, save to file, then decrypt later to read

    Hi,
    I'm new to encrypting data in JAVA, have spend a few days reading up about it
    and trying several methods, the methods I have got to work have pretty weak encryption.
    The code below is one I'd really like to get working properly but seem to be having trouble with
    Any point in the right direction, or what I am doing wrong would be great help.
    Cheers
    This code - Works fine.
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    public class JEncryption
         public static void main(String[] argv) {
              try{
                  KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
                  SecretKey myDesKey = keygenerator.generateKey();
                  Cipher desCipher;
                  // Create the cipher
                  desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                  // Initialize the cipher for encryption
                  desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
                  System.out.println("MyDesKey - " + myDesKey);
                  //sensitive information
                  byte[] text = "This is your password".getBytes();
                  /*String jim = text.toString();*/
                  System.out.println("Text [Byte Format] : " + text);
                  System.out.println("Conversion back from bytes - " + new String(text));        
                  System.out.println("Text : " + new String(text));
                  // Encrypt the text
                  byte[] textEncrypted = desCipher.doFinal(text);
                  System.out.println("Text Encryted : " + textEncrypted);
                  // Initialize the same cipher for decryption
                  desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
                  // Decrypt the text
                  byte[] textDecrypted = desCipher.doFinal(textEncrypted);
                  System.out.println("Text Decryted : " + new String(textDecrypted));
              }catch(NoSuchAlgorithmException e){
                   e.printStackTrace();
              }catch(NoSuchPaddingException e){
                   e.printStackTrace();
              }catch(InvalidKeyException e){
                   e.printStackTrace();
              }catch(IllegalBlockSizeException e){
                   e.printStackTrace();
              }catch(BadPaddingException e){
                   e.printStackTrace();
    }The trouble is I want to write the encrypted message into a text file, then read it again
    from another class.
    So I tryed this below, tryed break down the key, then trying to rebuild the key (so I can
    use it in another class once I get this right)
    As you can see down the bottom, the first "Text Decryted : " Message will only show the
    message it originally generate for this instance.
    BUT the second one fails when it trys to Decrypt the code I have given it from class, the key
    I've used with the 2nd one I have taken from another instance of running the program (the one
    were I got the encrypted message to be decryted)
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    public class Enc
         public static void main(String[] argv) {
              try{
                  KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
                  SecretKey myDesKey = keygenerator.generateKey();
                  String jimbo = "¡uŠß†ÈÂ[";
                  byte[] james = jimbo.getBytes();
                  String algorithm = "DES";
                  SecretKey secretkey = new SecretKeySpec(james, algorithm);
                  System.out.println("getEncoded() : " + new String(james));        
                  System.out.println("getAlgorithm() : " + algorithm);     
                  System.out.println("GET : " + secretkey);     
                  System.out.println("                    /");
                  Cipher desCipher;
                  // Create the cipher
                  desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                  // Initialize the cipher for encryption
                  desCipher.init(Cipher.ENCRYPT_MODE, secretkey);
                  System.out.println("MyDesKeyNEW = " + myDesKey);
                  //sensitive information
                  byte[] text = "[B@1b9ce4b".getBytes();
                  System.out.println("Text [Byte Format] : " + text);
                  System.out.println("Text : " + new String(text));
                  // Encrypt the text
                  byte[] textEncrypted = desCipher.doFinal(text);
                  System.out.println("Text Encryted : " + textEncrypted);
                  // Initialize the same cipher for decryption
                  desCipher.init(Cipher.DECRYPT_MODE, secretkey);
                  // Decrypt the text
                  byte[] textDecrypted = desCipher.doFinal(textEncrypted);
                  System.out.println("Text Decryted : " + new String(textDecrypted));
                  // Decrypt the text
                  byte[] textDecrypted2 = desCipher.doFinal(text)
                  System.out.println("Text Decryted : " + new String(textDecrypted2));
              }catch(NoSuchAlgorithmException e){
                   e.printStackTrace();
              }catch(NoSuchPaddingException e){
                   e.printStackTrace();
              }catch(InvalidKeyException e){
                   e.printStackTrace();
              }catch(IllegalBlockSizeException e){
                   e.printStackTrace();
              }catch(BadPaddingException e){
                   e.printStackTrace();
    }Do you think I'm going about this the right way, am I getting warm with it?
    Is there a better way to be doing this?
    Basically I want to take a string, encrypt it, save that to a text file, then decrypt it to read it
    later on.
    Any help would be fantastic,
    Cheers, good day to you :-)

    1) DES is now considered a fairly weak algorithm. You would do better to use AES.
    2) ECB is not considered very secure since it allows forgery though splicing of ciphertext. It is better to use one of the feedback modes such as CBC.
    3) This byte[] text = "[B@1b9ce4b".getBytes();must be wrong. The "[B@1b9ce4b" is the pseudo reference to a byte array and has nothing to do with the content of the byte array. It was obtained by using the toString() method on a byte array.
    4) If you are going to get the bytes of a String you should explicitly specify the encoding rather than rely on the default character encoding since this will depend on the platform being used. utf-8 is usually the best encoding.
    5) If you want to turn random bytes into a String, and encryption keys and cipher text are in effect random bytes, then they should be Base64, ASCII85 or Hex encoded. Just using new String(randomByte) is a sure way to get problems since not all character encoding have valid or unique characters for all bytes and byte sequences.
    6) Your exception handling at best naive.
    7)  Your code and comments indicate that you need to do some background reading. I can recommend "Beginning Cryptography with Java" by David Hook published by Wrox.
    8) There is a hint in your code that you are going to be using this to encrypt passwords. Encrypting passwords is considered insecure with the standard approach being to use a seeded Digest such SHA128.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Encrypting an XML file data

    Hi All
    I am new to Java security. I am stuck where i need to write the handler for the webservice.
    I need to encrypt/sign the XML data using the some certificate.
    I am having the certificate (pfx) and JKS file with me which i got from the web service producer.
    Could some one let me know how can i encrypt this XML with above certificate.
    Please let me know if you need some more information.
    Thanks
    Navneet

    Navneet_Nigam wrote:
    In the means while could you please answer my one question what is the differecne between sign the xml and encrypting the xml.Sign - to indicate that the XML has not be tampered with.
    Encrypt - to hide the content from prying eyes.
    I want XMl to be signed and encryptedOK.
    If you are serious about doing this work then you should learn a good bit more about cryptography. A good starting point is
    "Beginning Cryptography with Java" written by David Hook and published by Wrox.

  • Implementing SAPGUI / WebAS SSO on Solaris Platform

    Hi,
    We want to enable Single Sign on on SAPGUI and Web AS using the SNC Functionality available in SAP and we are on the SOLARIS Platform
    Does anyone have a step by step guide for this configuration
    Thanks
    Makarand

    As you will learn from the documents referenced above, you have to use a SAP-certified product from an external partner to implement SNC between SAPGUI and SAP servers on Solaris. To find out about certified SNC solutions, please go to the [SAP Software Solution Partner Catalog|http://sspcatalog.sap.com/catalog/index.jsp] and enter SNC as search term.
    Beside the steps to configure SNC in the SAP application on server and client, there will be additional configuration steps for the 3rd-party tools. The vendors usually provide good documentation on this. If you use SAPcryptolib for SNC between SAP servers, there is an advantage in using a solution compatible with SAPcryptolib, so that the configuration steps are the same.
    Peter

Maybe you are looking for

  • Need code for dynamic insertion of a MIME object(image) into WebDynpro View

    Hi experts, I am attempting to insert an image into a view at runtime, using lines of code. I know that this code must be present in the WDDOMODIFYVIEW method of that particular view. However I am not sure about the lines of code which can do this. C

  • Adding a new tab in existing screen

    Hi Folks I want to add a new tab in the screen 6100 t-code:LSO_PSV2. The new tab is a standard SAP field in the backend Tables. My client wants to see the field in the form of a tab on this tabbed subscreen. Points will be awarded for helpful answer

  • PS elements 2 problem

    After a system crash, I had to reinstall this prog. This in fact was very difficult to do - setup started, and then almost immediately stopped. After approx 10 tries, tsetup did continue and installed. Most things now seem okay, but batch processing

  • Photo Booth and Logitech Vision Pro

    Hi there I bought a Logitech Vision Pro Quick Cam since it is said to be compatible with OS X. It works fine on my mac with Skype, but both Photo Booth and iMovie won't recognize the camera. iChat on the other hand will work. I contacted Logitech and

  • Layout for SXI_MONITOR

    Hi, I didn't found anything like changing layout for SXI_MONITOR. Even I am not sure if there exists any option that is asked in the below question. Please help me out to solve the below question. Which views are possible if you are changing the layo