Decrypting PEM file using Triple DES

Hi all,
I am trying to decrypt a Triple DES encrypted RSAPrivateKey stored in PEM format in a file. How do I get the DES key to initialize the Cipher. I am using the following code to get the IV from the file and get the DES key using pass phrase. But I get the message
java.lang.SecurityException: Unsupported keysize or algorithm parameters
Can someone help me.
Thanks in advance,
Trilok.
// Gets the IV params from the RSAPrivate key PEM file.
// Uses the last 16 digits in this line to get the IV.
// DEK-Info: DES-EDE3-CBC,4A90C209D3A81791
private IvParameterSpec getIV(String s) { // here s = 4A90C209D3A81791
byte[] ivBytes = new byte[8];
for (int j=0; j<8; j++) {
ivBytes[j] = (byte)Integer.parseInt(s.substring(j*2, j*2 + 2), 16);
return new IvParameterSpec(ivBytes);
private SecretKeySpec getSecretKey(byte [] pwd, byte [] iv)
throws NoSuchAlgorithmException {
     byte[] keyMat = new byte[24];
     MessageDigest md = MessageDigest.getInstance("MD5");
     md.update(pwd);
     md.update(iv);
     byte[] data = md.digest();
     System.arraycopy(data, 0, keyMat, 0, 16);
     md.update(data);
     md.update(pwd);
     md.update(iv);
     data = md.digest();
     System.arraycopy(data, 0, keyMat, 16, 8);
     return new SecretKeySpec(keyMat, encAlg);
}

Hi trilok,
Please let me know what JCE provider you are using for decrypting the Key.
Please make sure that you have made the static or dynamic registration properly.
For Static registration:
Please go to JAVA_HOME/jre/lib/security/java.security
Please edit
security.provider.1=sun.security.provider.Sun
For Dynamic Registration
Security.addProvider(new com.sun.crypto.provider.SunJCE());
Also please refer this URL, which is the third party provider which supports RSA.
http://www.bouncycastle.org/latest_releases.html
I hope this will help you.
Thanks
Bakrudeen
Technical Support Engineer
Sun MicroSystems Inc, India

Similar Messages

  • How to encrypt excel file data using triple DES algorithm in oracle

    Hi,
    I would like to know the process or script to encrypt/decrypt the excel file data using triple DES algorithm in oracle.

    I'm not quite sure your requirement.... do you mean when uploading files to be stored in the database ?

  • Getting Error while decrypt a file using Blowfish algorithm

    I am using blowfish algorithm for encrypt and decrypt my file. this is my code for encrypting decrypting .
    while i am running program i am getting an Exception
    Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA12275)
    at Blowfishexe.main(Blowfishexe.java:65)
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.io.*;
    import org.bouncycastle.crypto.CryptoException;
    import org.bouncycastle.crypto.KeyGenerationParameters;
    import org.bouncycastle.crypto.engines.DESedeEngine;
    import org.bouncycastle.crypto.generators.DESedeKeyGenerator;
    import org.bouncycastle.crypto.modes.CBCBlockCipher;
    import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
    import org.bouncycastle.crypto.params.DESedeParameters;
    import org.bouncycastle.crypto.params.KeyParameter;
    import org.bouncycastle.util.encoders.Hex;
    public class Blowfishexe {
    public static void main(String[] args) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
              kgen.init(128);
              String keyfile="C:\\Encryption\\BlowfishKey.dat";
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
              System.out.println("key"+raw);
                   byte[] keyBytes = skey.getEncoded();
                   byte[] keyhex = Hex.encode(keyBytes);
                   BufferedOutputStream keystream =
    new BufferedOutputStream(new FileOutputStream(keyfile));
                        keystream.write(keyhex, 0, keyhex.length);
    keystream.flush();
    keystream.close();
    Cipher cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
              System.out.println("secretKey"+skeySpec);
    FileOutputStream fos=new FileOutputStream("C:\\Encryption\\credit11.txt");
              BufferedReader br=new BufferedReader(new FileReader("C:\\Encryption\\credit.txt"));
              String text=null;
              byte[] plainText=null;
              byte[] cipherText=null;
              while((text=br.readLine())!=null)
              System.out.println(text);
              plainText = text.getBytes();
              cipherText = cipher.doFinal(plainText);
              fos.write(cipherText);
              br.close();
              fos.close();
              cipher.init(Cipher.DECRYPT_MODE, skeySpec);
              FileOutputStream fos1=new FileOutputStream("C:\\Encryption\\BlowfishOutput.txt");
              BufferedReader br1=new BufferedReader(new FileReader("C:\\Encryption\\credit11.txt"));
              String text1=null;
              /*while((text1=br1.readLine())!=null)
                   System.out.println("text is"+text1);
                   plainText=text1.getBytes("UTF8");
                   cipherText=cipher.doFinal(plainText);
                   fos1.write(cipherText);
              br1.close();
              fos1.close();
    //byte[] encrypted = cipher.doFinal("This is just an example".getBytes());
              //System.out.println("encrypted value"+encrypted);*/
    Any one pls tell me how to slove my problem
    thanks in advance

    hi
    i got the solution. its working now
    but blowfish key ranges from 56 to448
    while i am writing the code as
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(448);
    this code is generating the key upto 448 bits
    but coming to encoding or decode section key length is not accepting
    cipher.init(Cipher.ENCRYPT_MODE, key);
    Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at Blowfish1.main(Blowfish1.java:46)
    i am getting this error
    what is the solution for this type of exception.
    thank you

  • How do I protect my FLV files? or How to encrypt and decrypt FLV files using AIR?

    Hi,
         I am working on an AIR application, which is developed on eLearning concept. The application mainly deals with flv files. The application contains a video player component, which will stream flv files from an Apache Server and played in my application. Here my concern is I would like to protect my flv files some how against users who may stream them from Apache Server and use them without my application.
         I thought of with an idea to do it. But I don't know whether it will work or not. So I am requesting for your suggestions and better ways to do this with a sample.
    Here is my thought:
    I would like to place the encrypted FLV files at Apache Server side [ Need to know how to encrpt the FLV files using Flex]
    As my AIR application send a request for a FLV file, the Apache server should send the decryption key and a stream of FLV file.
    AIR application should take the decryption key, stream of flv file and it should capable enough to decrypt the FLV file and play it in my application. [ But I don't know how to encrypt/decrypt FLV files through flex]
    I can do encryption of FLV files using Mac Address of Apache Server system and using Java. But I don't know how can I decrypt the same FLV file ( Encrypted using Mac Address and java ) at AIR application side.
    So I would be greatfull If any body help me in encrypting and decrypting of FLV file with a sample using Flex 3.0.
    Thanks
    Sudheer Puppala

    russellfromblackburn south wrote:
    Is it because the portable drive is NTFS format and the Mac wont recognise this? If so what do I do?
    Yes, this is exactly what is causing the problem. Macs cannot write to NTFS formatted drives, only read. You must move the documents to the internal HDD/SSD of the Mac to be able to edit them.
    Or, since you say you don't want to move the documents to the internal storage, you'll need to format the external HDD as FAT32.

  • Decrypt file using AES(32) by java program ?

    I have encrypted file using AES 32 bit and i have key. So I want to decrypt the file using Java program/ cryptography standards with that key.
    Anybody help highly appreciated.

    Yes that would make sense, cheers:
                 fw2.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
                 fw2.write("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
                   fw2.write("<html>");
                   fw2.write("<head>");
                   fw2.write("<title>Output</title>");
                   fw2.write("<link href=\"Styles.css\" rel=\"stylesheet\" type=\"text/css\">");
                   fw2.write("</head>");
                   fw2.write("<body>");
                   fw2.write("<div id='Border'>");
                   fw2.write("<div id='Background'>");
                   searchForSubFolder(file);
                   fw2.write("</div>");
                   fw2.write("</div>");
                   fw2.write("</body>");
                   fw2.write("</html>");This is working to some extent although the formatting from the css file is not working. Any ideas why this is? I am using divs determined by thee css to do things like the background colour.
    Thanks

  • Hi Freinds......How to Encrypt/Decrypt Text file in j2me

    Hello friendz.,,
    I m having problem with textfile exncryption decryption in j2me..
    Can abybode tell me how to encrypt/decrypt Text file using J2ME API's.......
    PLZ help me .......
    Thanx in advance
    regards,
    Parag

    http://www.mobilefish.com/developer/bouncycastle/bouncycastle.html
    http://www-128.ibm.com/developerworks/library/j-midpds.html

  • PGP Decryption Error (File is no valid PGP Message)

    Hi, I'm encountering an error while decrypting a pgp file.  Error is MP: exception caught with cause com.sap.aii.af.lib.mp.module.ModuleException: File is no valid PGP Message, could not apply decryption.
    I have tested decrypting the file using an external tool and was able to decrypt it but not in PI.  Below is my configs in sender commChannel (Note: no file content conversion is involved).  Any ideas on how to resolve this? Thank you.

    Hi Sarah, thanks for the response. I tried arranging the sequence as you've suggested but once saved, it will re-arrange to the old order as below:
    keyRootPath
    ownPrivateKey
    partnerPublicKey
    pwdOwnPrivateKey
    With regards to running XPI Inspector Tool, i will install it first.
    For the meantime, are there other suggestions?
    Thank you.

  • Decrypt The.spenc file using VB or C#

    Hi,
    I have one encrypted file with extension .spenc. It comes with decryption key. I would like to decrypt it by using that key in SSIS. I suppose I have to do using Script component. How can I do that using Script Component.
    Any Idea?
    Regards,
    Mustafa
    MH

    Hi Arthur,
    Thanks for your reply. I have managed to get this one by getting some help on MSDN but It is not going to the CrptoReader Class not sure Why? Am I missing something? I have debugged and getting the values in the variables from SSIS.
    Imports System
    Imports System.Data
    Imports System.Math
    Imports Microsoft.SqlServer.Dts.Runtime
    Imports System.IO
    Imports System.Object
    Imports System.Security.Cryptography
    Imports System.IO.Compression
    <System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
    <System.CLSCompliantAttribute(False)> _
    Partial Public Class ScriptMain
    Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    Enum ScriptResults
    Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
    Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum
    Public Sub Main()
    ' Add your code here
    Dim inputFile As String
    Dim outputFile As String
    Dim encoding As String
    Dim PrivateKeyInXML As String
    'Mapping variables from SSIS
    inputFile = Dts.Variables("Item1Path").Value.ToString()
    outputFile = Dts.Variables("OutputFile").Value.ToString()
    encoding = Dts.Variables("Encoding").Value.ToString()
    PrivateKeyInXML = Dts.Variables("PrivateKey").Value.ToString()
    Dts.TaskResult = ScriptResults.Success
    End Sub
    Public Class CryptoReader
    Private _FileStream As FileStream
    Private _CryptoStream As CryptoStream
    Private _ZipStream As GZipStream
    Private _RSAPrivateKeyinXML As String
    Dim _CryptoAgent As New System.Security.Cryptography.AesCryptoServiceProvider
    Sub New(ByVal inputFile As String, ByVal outputFile As String, ByVal encoding As System.Text.Encoding, ByVal PrivateKeyInXML As String)
    _RSAPrivateKeyinXML = PrivateKeyInXML
    'Create the crypto agent
    _CryptoAgent = AesCryptoServiceProvider.Create
    'Open cypher text for reading in
    _FileStream = New FileStream(inputFile, FileMode.Open)
    ReadHeaderFromFile() 'write out aes key to header
    'Create the stream to decrypt the AES part of the file
    _CryptoStream = New CryptoStream(_FileStream, _CryptoAgent.CreateDecryptor, CryptoStreamMode.Read)
    _ZipStream = New GZipStream(_CryptoStream, CompressionMode.Decompress)
    'setup complete - run decrypt to unprotect the rest of the file
    DecryptFile(outputFile)
    Flush()
    Close()
    Dispose()
    End Sub
    Public Sub Close()
    _CryptoStream.Close()
    _ZipStream.Close()
    _FileStream.Close()
    End Sub
    Public Sub Dispose()
    _CryptoStream.Dispose()
    _ZipStream.Dispose()
    _FileStream.Dispose()
    End Sub
    MH

  • Triple DES CBC Encryption using an Initial Vector

    How can triple DES encryption in CBC be done using the javacard package and not javax?
    Will this do?
                   cipher3DESCBCDebSesKey1.init( key, Cipher.MODE_ENCRYPT, initVector, (short) 0, (short) 8);
                   cipher3DESCBCDebSesKey1.doFinal( input, (short) 0, (short) 16, SesKey, (short) 0 );
    After all the initialization, will the doFinal already give me the result of triple DES using CBC? or do I have to init* and doFinal* three times?
    Also, I used the no pad setting for this one.
    cipher3DESCBCDebSesKey1 = Cipher.getInstance( Cipher.ALG_DES_CBC_NOPAD, false );

    The fact that only the first block is corrupt is indicative that I you are not using the same IV on both sides. This is confirmed by your PHP code that seems to generate a random IV so your chance of getting the same IV on both sides is just about zero.

  • Single sign on using AES or Triple DES algorithm.

    Hello all-
    At my client place we have to setup a Single Sign On Functionality to an external system. The link will be on the portal page for the employees to click. This functioanlity has to be done by either AES (Advanced Encryption Algorithm) or Triple DES algorithm.
    When the user clicks the SSO link on the portal page, the BSP application should implement any of these two above mentioned encryption algorithms and post the encrypted key appended to the third party URL. Then the third party system will decrypt and verify the user who is requesting the information and accordingly either allow or deny.
    If anyone has any info on this please revert back.
    Thank you very much for the help.
    Ramesh.

    Hi Ramesh,
    Did u get any clarification regarding Standard Triple DES algorithm.
    If yes,Please let me know.
    Thanks,
    JOhny lever

  • Help needed in encrypting and decrypting a file

    Hello,
    I just started looking into the Java Security.I need to encrypt a file using any popular alogrithm like RSA or DES and write it to disk.and again decrypt this file at a later time when needed.
    I was checking out with different ways of doing so,but found it difficult to persist the key some where.
    Could some one help me in this regard,with a tutorial or a sample program where I will be able to give cleartext file as an input and get a ciphered text file as output and vice versa?

    Probably the simplest solution is to use password-based encryption (PBE). See http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html#PBEEx
    for an example.

  • Error while encrypting the xml file using asymmetric cipher...pls help

    i am encryption the xml file using asymmetric cyper....
    in one class , i am generating private key and public key using "RSA" algorithm..using 1024 byte initialization...
    it is generating properly...
    and after that in second class i am encrypting the xml file using "DESede" algorithm and i am using public key of above class..
    but i am getting exceptione :
    java.security.InvalidKeyException: Invalid key length: 162 bytes
    at com.sun.crypto.provider.DESedeCipher.engineGetKeySize(DashoA6275)
    at javax.crypto.Cipher.init(DashoA6275)
    at XmlEncryption.getEncryptedData(XmlEncryption.java:147)
    at XmlEncryption.encryptCompleteXmlFile(XmlEncryption.java:123)
    at demoXmlEncApp.simulateBookSellersEnd(demoXmlEncApp.java:72)
    at demoXmlEncApp.main(demoXmlEncApp.java:29)
    so, what is that ?
    i want to use RSA algo for key generatiion and DESede for cipher initialization .
    is there any site for where source code of xml file encryption using asymmetric cipher is available?
    pls, help me.....

    Sachin,
    What sabre150 is trying to explain to you, is that encrypting data (such as an XML file) is a 2-step process. In the first step, you generate a symmetric key (such as DES, 3DES, AES) and encrypt your file with this key (and the appropriate mode and padding).
    In order to ensure that your encrypted data cannot be decrypted by unauthorized individuals, you now need to protect the symmetric key. Encrypting your symmetric key with another symmetric key does not solve the problem, since you have a chain of symmetric keys that need to be encrypted into infinity.
    Cryptographers solve this problem by encrypting the symmetric key with an asymmetric key, such as as RSA. To perform this second step, you generate an RSA key-pair, encrypt the symmetric key you generated in step 1 with the Public key of the RSA key-pair, and give the recipient of the encrypted XML file, access to the Private key of the RSA key-pair as well as the encrypted symmetric key.
    The recipient, then uses the RSA Private key to decrypt the symmetric key first, and then uses the "plaintext" symmetric key to decrypt the XML file.
    What sabre150 was also attempting to explain to you, is the traditional way of transporting an encrypted "blob" that consists of data + symmetric key. With a modern key-management system, combining the two would be unnecessary.

  • How Encrypt a File Using Key?

    Hi Guys,
    Here is my problem. I have to create a bank's document encrypted to send to a legacy system. ( Using a KEY to validate the roll process)
    I'm thinking to use two scenarios:
    1 - Generate the file via ABAP and sent it to a folder in a server to be consuming - SAP ERP.
    2 - Generate the file via ABAP, sent it to PI encrypt it via Java Mapping and sent it to a server.
    ABAP
    First question.
    There is a way to generate this file using SHA1 using a Key as parameter?
    (CALCULATE_HASH_FOR_CHAR)
    Second one.
    How can I decrypt this file to test?
    Third.
    There is others ways to encrypt a file via SAP ERP? UTF-8 and BASE32 are not encrypt codes. They are encoding code.
    PI
    First
    There is a library or other way to encrypt a file without implement a Java Mapping?
    Tnks.

    > There is a way to generate this file using SHA1 using a Key as parameter?
    Why don't you simple search the forum with "SHA1" term, you'd get the answer in an instant
    > How can I decrypt this file to test?
    > There is others ways to encrypt a file via SAP ERP? UTF-8 and BASE32 are not encrypt codes. They are encoding code.
    What encryption do you need?
    > But I would like to know if are these methods algorithms as DES, AES, RSA... or others ?
    Couldn't you say it at the beginning!
    By simply looking at CL_HARD_WIRED_ENCRYPTOR methods, we see that the encryption mechanism is very simple (I'm not expert so I can't tell what it is), I wouldn't rely on it...
    I recommend you to read [Note 662340 - SSF Encryption Using the SAPCryptolib|http://service.sap.com/sap/support/notes/662340]. There are also some documentation, security guides on sap library and sap marketplace.
    Edited by: Sandra Rossi on Jul 13, 2010 6:51 PM

  • Read PKCS8 encrypted key with Triple DES

    Hi, I have a RSA private key in a PKCS8 file, encrypted with Triple DES. I can obtain the RSA private key with the command:
    openssl pkcs8 -inform der -v2 des3 -passin pass:mypass -in private.key > rsakey.key
    Then I can read it in Java using bouncycastle classes:
                    Security.addProvider(new BouncyCastleProvider());
              String file = "rsakey.key";
              PEMReader pr = new PEMReader(new FileReader(file));
              Object obj = pr.readObject();
              KeyPair kp = (KeyPair) obj;
              PrivateKey privateKey = kp.getPrivate();My question is:
    How can I use the bouncycastle classes to replace the openssl command, So all the process stays in java.
    Thanks in advance
    Rich

    The class for this is javax.crypto.EncryptedPrivateKeyInfo but I seem to be having trouble getting it to work (I've posted about my problem in the Cryptography forum).

  • Utility to generate the triple des (3DES) encrypted password in wl 6.1?

    To take advantage of the encrypted passwords in config.xml, as of wl 6.1, is
    there a weblogic utiltiy or api tha could be used to encrypt plaintext into
    the triple-des symmetric key PRIOR to having an SA or DBA type it into the
    console? This would help me greatly in the deployment and security of
    passwords.
    Thanks in Advance,
    Steve Rogers

    Hi,
    Thank you for your question.
    I am trying to involve someone familiar with this topic to further look at this issue. There might be some time delay. Appreciate your patience.
    Thank you for your understanding and support.
    Best Regards,
    Aiden
    Aiden Cao
    TechNet Community Support

Maybe you are looking for

  • Unable to install Acrobat Prof. X

    When finished all fill in parameters and click on install button, no response and nothing display. Checking the install log and there was no log file created in location c:\Program Files\Common Files\Adobe\Installer\. I don't know what is wrong. Task

  • Dynamic Table Header in WebI

    Hi community I'm currently facing quite a challange with WebI: I have (simplified) the following data structure in my Universe (which ist built upon a BEx Query): - Customer - Calendar Day - Calendar Week - Calendar Month - Turnover Now, the customer

  • Moving to the 2nd page on a web site and it turns white or black

    This just seems to happen on loan sites, after I fill in the filed on the web sites first page. going to the second page the only thing that comes up is either a white page with nothing on it, or a charcoal black page with a link saying something abo

  • Information for GR in particular PO

    Hi Gurus, Is there any report, in which system will give the GR No. and Posting date in a list of POs.? Means, i will give some PO Nos in selection parameters and i want if GR is done, then system should show me the gr no. and posting date. Please te

  • CIN and 3 Plants having a common Excise Registration

    Hi Experts, Please provide the solution for this. I have an organisation which has 3mfg units.I want to treat this as Plants 1,2&3 Most of the raw materials are common for all the three plants.Also they have one Excise registration for all 3 units.My