Encrypt RSA/ECB/OAEPWithSHA1AndMGF1Padding

hi,
i have to encrypt a simple string with RSA/ECB/OAEPWithSHA1AndMGF1Padding but i have no idea how to start this in java. there are too much security and crypto classes :8
i hope sombody can help me.
Edited by: z3ky on Dec 6, 2007 3:17 PM

First, make sure you have an adequate understanding of cryptography. Java cryptography classes will be hard to understand without it. For example, normally RSA is not used to encrypt (or sign) data directly. If you don't know this or don't know why, then you need to study cryptography more.
I guess the heart of the encryption classes is the Cipher class. Thus, you would start with with something like Cipher rsaCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");Next, you need to initialize the cipher object with a mode, a key, and possible other items like an IV, depending on the nature and mode of the encryption algorithm. Here is a sample that generates an RSA Keypair and then initializes the Cipher object:        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = kpg.generateKeyPair();
        RSAPublicKey rsaPubkey = (RSAPublicKey) kp.getPublic();
        RSAPrivateKey rsaPrivkey = (RSAPrivateKey) kp.getPrivate();
        rsaCipher.init(Cipher.ENCRYPT_MODE, rsaPubkey);Next, you have to decode your string into a byte array, then encrypt the array, and finally do something with the encrypted data.        String sample = "This is a short string";
        byte[] sampleBytes = sample.getBytes("UTF-8");
        byte[] sampleCipher = rsaCipher.doFinal(sampleBytes);
        System.out.println(Arrays.toString(sampleCipher));

Similar Messages

  • "Cannot find any provider supporting RSA/ECB/PKCS1Padding" in jdk5

    i use SSLSocket, HttpsURLConnection in program , run well in jdk1.4 but
    get wrong in jdk1.5.0_06, saying "Cannot find any provider supporting RSA/ECB/PKCS1Padding".
    i also try to use the "Unlimited Strength Jurisdiction Policy Files 5.0", but still not work.
    anyone knows why?
    thanks.

    I need more info to tell you exactly. But here are some thngs that might not be working.
    1st let me say I am assuming you are trying RSA encryption?
    1) You have an external JCE provider which provides RSA support installed on your machine using the security properties file. An applet would use a different properties file if you are using either RAW applet or the plugin. You need to add the provider explictly. Aka Security.addProvider(new org.cryptix.jce.Criptix());
    2) The external provider's jar file is not being downloaded with your applet code. Note that the Sun Java plugin does not use the same jre/lib/ext directory as does the JDK.
    3) Some sort of security violation in the SecurityManager of the applet engine if you are not using the Sun Java Plugin.
    Those are just guesses. but it might help if you were to inform us as to what RSA function youa re trying to do. AKA Signature or Cipher.
    Signatures would be a bit more complicated as at least JDK 141 and above have the SunRsaSigner built in. Again if you are using RAW applets (netscape/IE engine) then that would be the problem. (aka no provider installed).

  • RSA ECB jvm 1.4.2

    This is a topic rewritten because i add the code tag :(
    Hi, im trying to do a simple PKCS7 RSA encryption, i only
    need that a String can be encripted using RSA and padding
    with PKCS7 but, i cant. I read a lot of topic in this forum, but
    no one aparently do just i need...
    I read that bouncy castle, has a special support for get
    a Cipher instance that use the RSA for encrypt and
    PKCS7 for padding i read at the bouncy castle doc
    something like that:
    Security.addProvider(new BouncyCastleProvider());
    cipher = Cipher.getInstance("RSA/EBC/PKCS7", "BC");After that i get a key instance, and i generate the
    public key and the private key:
    KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");
    kg.initialize(512);
    KeyPair key = kg.generateKeyPair();
    Key publicKey = key.getPublic();
    Key privateKey = key.getPrivate();And finally i do the encryption:
    byte[] input = plainText.getBytes("UTF8");
    Cipher cipher = getCipher();
    cipher.init(Cipher.ENCRYPT_MODE, encriptationKey);
    byte[] cry = cipher.doFinal(input);
    byte[] encriptado = Base64.encode(cry);But when i run the method i see in the output console
    this message:
    java.lang.IllegalArgumentException: can't support mode EBC at org.bouncycastle.jce.provider.JCERSACipher.engineSetMode(JCERSACipher.java:112)
    at javax.crypto.Cipher.a(DashoA6275)
    at javax.crypto.Cipher.getInstance(DashoA6275)
    at org.EncriptionService.getCipher(EncriptionService.java:20)
    at org.EncriptionService.encript(EncriptionService.java:66)
    at org.EncriptionService.main(EncriptionService.java:40)
    java.lang.NullPointerException
    at org.EncriptionService.encript(EncriptionService.java:68)
    at org.EncriptionService.main(EncriptionService.java:40)Anyone can help me please ?? I read documentation at
    the bouncy castle, but i find nothing... :(
    Please if anyone has a little piece of code that encrypt a
    String with RSA and PKCS7 please posted it.
    thank you.

    See my response to your other post.

  • Ironport Email Encryption及RSA Email Data Loss Prevention在Ironport中分别起哪些作用?

    What are the functions do in both Ironport Email Encryption and RSA Email Data Loss Prevention in Ironport?

    As noted there is no good solution. If it has never been backed up, then when you restore through iTunes on a computer, all of the information on it will be erased. Restoring it is the only way to get it working again.

  • Problem in decrypting the code

    I have written the following code for decryption
    String inputString = "5B5E0A35FBD295AB923D872BC1CBCF45307FACDA881978ACBE65C21FDF63658F61B48EE3C99BBDB0E51B9F1498289305526D82EA2D52D681993E3AD499F2887E82D35CC9CD9EF436B8A9E587CC3E2A50CABFAB39824632F7ECDCDFAE7AC0A7BEAD0767D83D3E3E0BFAAA3F053E5678901ABCDE1B8581310F6513D0547290F6C9E";
    String inputKey = "243fbde01df0684ed5b49f1035137225fcca9ba960e5e979e9cb8bee345f2f258678901acbd05c4f084c0373d3300432b186e03c56bd93bacb4ba634ad2b407b18f2985497eaa1e635152d7e9814ee469a94115109841758f67e61885d412dcc47efd670e156700e6df84dcadd41bc0588a8b4babcde54387d742e96308d66a1";
    String labelString = "0000000819";
    byte [] input = hexstringToByteArray(inputString);
    byte[] keyBytes = hexstringToByteArray(inputKey);
    byte[] label = padWithZeros(hexstringToByteArray(labelString));
    Security.addProvider(new BouncyCastleProvider());
    BigInteger privateKeyInt = new BigInteger(keyBytes);
    Cipher bcCipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
    OAEPParameterSpec defaultOaepSpec = OAEPParameterSpec.DEFAULT;
    OAEPParameterSpec oaepSpec = new OAEPParameterSpec(defaultOaepSpec.getDigestAlgorithm(),
    defaultOaepSpec.getMGFAlgorithm(),
    defaultOaepSpec.getMGFParameters(),
    new PSource.PSpecified(label));
    java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA", "BC");
    java.security.Key bcPrivateKey = keyFactory.generatePrivate((new RSAPrivateKeySpec(privateKeyInt,new BigInteger("3"))));
    // SecureRandom = new SecureRandom()
    bcCipher.init(Cipher.DECRYPT_MODE, bcPrivateKey,oaepSpec);
    byte[] em = bcCipher.doFinal(input);
    System.out.println(byteArrayToHexString(em));
    Output :-
    Exception in thread "main" java.lang.IllegalArgumentException: unknown parameter type.
         at org.bouncycastle.jce.provider.JCERSACipher.engineInit(JCERSACipher.java:247)
         at javax.crypto.Cipher.init(DashoA13*..)
         at javax.crypto.Cipher.init(DashoA13*..)
         at PublicMain.main(PublicMain.java:44)
    I have to use OEAP padding
    pls help me solve this problem thanks in advance

    I have written this code for decryption and tried the earlier problem by resolving proper jar file
    String inputString = "5B5E0A35FBD295AB923D872BC1CBCF45307FACDA88598153052DC21FDF6365345678AEBCC99BBDB0E51B9F1498289305526D82EA2D52D681993E3AD499F2887E82D35CC9CD9EF436B8A9E587CC3E2A50CABFAB39824632F7ECDCDFAE7AC0A7BEAD0767D83D3E3E0BFAAA3F";
    /* private key*/String inputKey = "243fbde01df0684ed5b49f1035137225fcca9ba960e5e979e9cb8bee345f2f258344795904605c4f084c037456cabefc4186e03c56bd93bacb4ba634ad2b407b18f2985497eaa1e635152d7e9814ee469a94115109841758f67e61885d412dcc47efd670e156700e6df84dcadd41bc0588a8b4b19bb509409d742e96308d66a1";
    String labelString = "40156ca44f22db70b7f852eec9d57ce10000000913"; //Unencrypted header may change
    String publicKey = "9e4004e8ab15bad1ec47059b86a50f5f46334da008fded08b7fe300d1a14a8f926d8abcde13456786282335c03eee04559861043b8a1f7db4ee79f2a17a8aff278dee0ebc997a48668fb99ec6d901b3e5723318bbdc0586f05196b4603b36b2d8eb62b52395684b26d50bb6df19bc8b72bb7eec359a68651842e739e52cbc05027";
    byte [] input = hexstringToByteArray(inputString);
    byte[] keyBytes = hexstringToByteArray(inputKey);
    byte[] publicKeyBytes = hexstringToByteArray(publicKey);
    byte[] label = hexstringToByteArray(labelString);
    System.out.println(input.length);
    Security.addProvider(new BouncyCastleProvider());
    BigInteger privateKeyInt = new BigInteger(keyBytes);
    BigInteger publicKeyInt = new BigInteger(publicKeyBytes);
    Cipher bcCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC");
    OAEPParameterSpec defaultOaepSpec = OAEPParameterSpec.DEFAULT;
    OAEPParameterSpec oaepSpec = new OAEPParameterSpec(defaultOaepSpec.getDigestAlgorithm(),
    defaultOaepSpec.getMGFAlgorithm(),
    defaultOaepSpec.getMGFParameters(),
    new PSource.PSpecified(label));
    java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA", "BC");
    java.security.Key bcPrivateKey = keyFactory.generatePrivate((new RSAPrivateKeySpec(publicKeyInt,privateKeyInt)));
    // SecureRandom = new SecureRandom()
    /* PrivateKey p = keyFactory.generatePrivate((new RSAPrivateKeySpec(publicKeyInt,privateKeyInt)));
    System.out.println(p.toString());*/
    bcCipher.init(Cipher.DECRYPT_MODE, bcPrivateKey,oaepSpec);
    /*RSAEngine rsa = new RSAEngine();
    OAEPEncoding a = new OAEPEncoding(rsa,new SHA1Digest(),label);
    rsa.init(false, (CipherParameters) p);
    byte[] output = a.decodeBlock(input, 0, input.length); */
    byte[] em = bcCipher.doFinal(input);
    System.out.println(byteArrayToHexString(em));
    But now it is giving the following exception :
    Exception in thread "main" org.bouncycastle.crypto.DataLengthException: input too large for RSA cipher.
         at org.bouncycastle.crypto.engines.RSACoreEngine.convertInput(Unknown Source)
         at org.bouncycastle.crypto.engines.RSABlindedEngine.processBlock(Unknown Source)
         at org.bouncycastle.crypto.encodings.OAEPEncoding.decodeBlock(Unknown Source)
         at org.bouncycastle.crypto.encodings.OAEPEncoding.processBlock(Unknown Source)
         at org.bouncycastle.jce.provider.JCERSACipher.engineDoFinal(Unknown Source)
         at javax.crypto.Cipher.doFinal(DashoA13*..)
         at PublicMain.main(PublicMain.java:55)
    Please help me correcting the input length
    Thanks in advance

  • Installing the OpenSSO STS Server On Tomcat but have error

    hello everyone ,
    I try to install the OpenSSO STS Server On Tomcat , but not successful.
    softwares:
    tomcat 6.0.32
    jdk1.6.0_18
    openssosts.war
    i Deploy the OpenSSO STS WAR File on Tomcat is ok and it works
    but at the Welcome page configure the configuration time , error is like that:
    設定ディレクトリ C:/temp/openssosts をチェックしています。...成功しました。
    OpenSSO 設定ストアのインストール...成功しました RSA/ECB/OAEPWithSHA1AndMGF1Padding。
    C:/temp/openssosts/opends での OpenSSO 設定ストアのインストールAMSetupServlet.processRequest: errorjava.lang.NullPointerException
         at java.security.MessageDigest.update(MessageDigest.java:293)
         at java.security.MessageDigest.digest(MessageDigest.java:368)
         at org.opends.server.crypto.CryptoManagerImpl.getInstanceKeyID(CryptoManagerImpl.java:628)
         at org.opends.server.crypto.CryptoManagerImpl.publishInstanceKeyEntryInADS(CryptoManagerImpl.java:644)
         at org.opends.server.crypto.CryptoManagerSync.<init>(CryptoManagerSync.java:126)
         at org.opends.server.core.DirectoryServer.startServer(DirectoryServer.java:1446)
         at org.opends.server.util.EmbeddedUtils.startServer(EmbeddedUtils.java:89)
         at com.sun.identity.setup.EmbeddedOpenDS.startServer(EmbeddedOpenDS.java:266)
         at com.sun.identity.setup.EmbeddedOpenDS.setup(EmbeddedOpenDS.java:200)
         at com.sun.identity.setup.AMSetupServlet.setupEmbeddedDS(AMSetupServlet.java:537)
         at com.sun.identity.setup.AMSetupServlet.setupSMDatastore(AMSetupServlet.java:573)
         at com.sun.identity.setup.AMSetupServlet.configure(AMSetupServlet.java:649)
         at com.sun.identity.setup.AMSetupServlet.processRequest(AMSetupServlet.java:379)
         at com.sun.identity.setup.AMSetupServlet.doPost(AMSetupServlet.java:323)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at com.sun.identity.setup.AMSetupFilter.doFilter(AMSetupFilter.java:120)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
         at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
         at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
         at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
         at java.lang.Thread.run(Thread.java:619)
    help , thanks.

    thanks.
    my OpenSSO STS's version is Oracle OpenSSO STS 11.1.1.3.0. Is that Ok?
    PC's locale language is japanese. Now try to change to English to see.
    The same error happned ,and log is like this:
    Checking configuration directory C:/temp/openssosts....Success.
    Installing OpenSSO configuration store...Success RSA/ECB/OAEPWithSHA1AndMGF1Padding.
    Installing OpenSSO configuration store in C:/temp/openssosts/opendsAMSetupServlet.processRequest: errorjava.lang.NullPointerException
         at java.security.MessageDigest.update(MessageDigest.java:293)
         at java.security.MessageDigest.digest(MessageDigest.java:368)
         at org.opends.server.crypto.CryptoManagerImpl.getInstanceKeyID(CryptoManagerImpl.java:628)
         at org.opends.server.crypto.CryptoManagerImpl.publishInstanceKeyEntryInADS(CryptoManagerImpl.java:644)
         at org.opends.server.crypto.CryptoManagerSync.<init>(CryptoManagerSync.java:126)
         at org.opends.server.core.DirectoryServer.startServer(DirectoryServer.java:1446)
         at org.opends.server.util.EmbeddedUtils.startServer(EmbeddedUtils.java:89)
         at com.sun.identity.setup.EmbeddedOpenDS.startServer(EmbeddedOpenDS.java:266)
         at com.sun.identity.setup.EmbeddedOpenDS.setup(EmbeddedOpenDS.java:200)
         at com.sun.identity.setup.AMSetupServlet.setupEmbeddedDS(AMSetupServlet.java:537)
         at com.sun.identity.setup.AMSetupServlet.setupSMDatastore(AMSetupServlet.java:573)
         at com.sun.identity.setup.AMSetupServlet.configure(AMSetupServlet.java:649)
         at com.sun.identity.setup.AMSetupServlet.processRequest(AMSetupServlet.java:379)
         at com.sun.identity.setup.AMSetupServlet.doPost(AMSetupServlet.java:323)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at com.sun.identity.setup.AMSetupFilter.doFilter(AMSetupFilter.java:120)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
         at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
         at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
         at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
         at java.lang.Thread.run(Thread.java:619)
    Edited by: user13705486 on 2011/02/08 17:36

  • RSA with Cryptix: can encrypt but not decrypt? Please help.. :)

    Hi all,
    I've been trying to do RSA encryption/decryption using a pair of keys created with keytool. I've been able to encrypt some bytes, but when I attempt to decrypt the results immediately using the private key, I received the following exception:
    IllegalBlockSizeException: RSA: Cipher in DECRYPT state with an incomplete final block
    Please can anyone save me out of my misery and shed some light on this problem? Thanks a great deal in advance.
    Best Regards,
    Kenshin
    Here are the code snippets:
    // 1. imported APIs:
    import javax.net.ssl.*;
    import java.io.*;
    import java.security.*;
    import java.security.interfaces.*;
    import java.security.spec.*;
    import java.security.cert.*;
    import java.security.cert.Certificate;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import cryptix.provider.Cryptix;
    import xjava.security.Cipher;
    import xjava.security.CipherInputStream;
    import xjava.security.CipherOutputStream;
    import xjava.security.interfaces.*;
    import cryptix.provider.rsa.*;
    // 2. Getting the Public Key from the created cert:
    File certFile = new File("c:/keystore/jbossSSL.cer");
    FileInputStream certFileInStream = new FileInputStream(certFile);
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    Certificate cert = (Certificate)cf.generateCertificate(certFileInStream);
    RSAPublicKey serverPublicKey = (RSAPublicKey)cert.getPublicKey();
    // 3. Doing the encryption:
    Security.addProvider( new cryptix.provider.Cryptix());
    Cipher cipherInstance = Cipher.getInstance("RSA/ECB/PKCS7", "Cryptix");
    CryptixRSAPublicKey vCryptixRSAPubKey = (CryptixRSAPublicKey) new RawRSAPublicKey(serverPublicKey.getPublicExponent());
    cipherInstance.initEncrypt(vCryptixRSAPubKey);
    System.out.println("String to be encypted: " + sRandomString);
    // Sample of what is printed: String to be encypted: 2201162506010696613
    ByteArrayInputStream clearTextInStream = new ByteArrayInputStream(sRandomString.getBytes());
    CipherInputStream cInStream = new CipherInputStream(clearTextInStream, cipherInstance);
    ByteArrayOutputStream cipherTextOutStream = new ByteArrayOutputStream();
    CipherOutputStream cOutStream = new CipherOutputStream(cipherTextOutStream, cipherInstance);
    byte[] buffer = new byte[8192];
    int length;
    while((length= cInStream.read(buffer))!=-1)
    cOutStream.write(buffer, 0, length);
    cOutStream.close();
    cInStream.close();
    cipherTextOutStream.close();
    clearTextInStream.close();
    String sEncodedString = new String(cipherTextOutStream.toByteArray());
    System.out.println("String encrpted: " + sEncodedString);
    // Sample of what is printed: String to encrpted: 2 2 01 1 6 25 0 6 01 0 6 96 6 1 3&#9786; &#9787;&#9787;
    // 4. Getting the Private key from the keystore
    FileInputStream in = new FileInputStream("C:/keystore/jbossSSL.keystore");
    KeyStore catalinaKeyStore = KeyStore.getInstance("jks");
    catalinaKeyStore.load(in, "jbossSSL".toCharArray());
    RSAPrivateKey privateK = (RSAPrivateKey)catalinaKeyStore.getKey("jbossSSL", "jbossSSL".toCharArray());
    CryptixRSAPrivateKey vCryptixRSAPriKey = (CryptixRSAPrivateKey) new RawRSAPrivateKey(privateK.getPrivateExponent(), privateK.getModulus());
    cipherInstance.initDecrypt(vCryptixRSAPriKey);
    // 5. Doing the decryption:
    ByteArrayInputStream cipherTextInStream = new ByteArrayInputStream(sEncodedString.getBytes());
    cInStream = new CipherInputStream(cipherTextInStream,cipherInstance);
    ByteArrayOutputStream clearTextOutStream = new ByteArrayOutputStream();
    cOutStream = new CipherOutputStream(clearTextOutStream,cipherInstance);
    while((length= cInStream.read(buffer))!=-1)
    cOutStream.write(buffer, 0, length); >> exception thrown here
    cOutStream.close();
    cInStream.close();
    clearTextOutStream.close();
    cipherTextInStream.close();
    String sDecodedString = new String(clearTextOutStream.toByteArray());
    System.out.println("Stringdecrpted: " + sDecodedString);

    Here is working RSA example Maybe will help you. (may has a few typing errors becosu I rmoved some confidential data ;) )
    import java.util.*;
    import javax.swing.*;
    import java.io.*;
    import java.security.*;
    import javax.crypto.Cipher;
    import xjava.security.*;
    import cryptix.provider.Cryptix;
    import xjava.security.interfaces.CryptixRSAPublicKey;
    import xjava.security.interfaces.CryptixRSAPrivateKey;
    import xjava.security.KeyGenerator;
    import xjava.security.SecretKey;
    public class testcipher extends javax.swing.JFrame{
        /** Creates new test */
        public testcipher() throws Exception {
        * @param args the command line arguments
        public static void main(String [] args) throws Exception  {
            Provider pd = new cryptix.provider.Cryptix();
            Security.addProvider(pd);
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "Cryptix");
            kpg.initialize(1024, new java.security.SecureRandom());
            System.out.println("Generating key pair...");
            KeyPair kp = kpg.genKeyPair();
            System.out.println("Key pair generated...");
            xjava.security.Cipher cp = xjava.security.Cipher.getInstance("RSA/ECB/PKCS7", "Cryptix");
            cp.initEncrypt(kp.getPublic());
            FileInputStream fis = new FileInputStream("c:\\temp\\b2b\\index.htm");
            CipherInputStream cin = new CipherInputStream(fis, cp);
            FileOutputStream fout = new FileOutputStream("C:\\temp\\b2b\\enc.htm");
            CipherOutputStream cout = new CipherOutputStream(fout, cp);
            byte[] buffer = new byte[8192];
            int length;
            while((length=cin.read(buffer))!=-1)
                cout.write(buffer, 0, length);
            cout.close();
            cin.close();
            fout.close();
            fis.close();
            cp.initDecrypt(kp.getPrivate());
            fis = new FileInputStream("c:\\temp\\b2b\\enc.htm");
             cin = new CipherInputStream(fis, cp);
             fout = new FileOutputStream("C:\\temp\\b2b\\dec.htm");
             cout = new CipherOutputStream(fout, cp);
                    while((length=cin.read(buffer))!=-1)
                cout.write(buffer, 0, length);
            cout.close();
            cin.close();
            fout.close();
            fis.close();
    }

  • Help with RSA Encryption using SATSA

    Hello,
    I am a new to writing code on J2ME . I am trying to encrypt data using
    RSA public key on J2ME using SATSA.
    I generated the public key using openssl in the PEM format and stored the
    key (mypublickey) as a Base64 decoded byte array in my code.
    Next, I did the following:
    X509EncodedKeySpec test - new X509EncodedKeySpec(mypublickey);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(test);
    I used this key to encrypt as follows:
    cipher c = Cipher.getInstance("RSA");
    c.init(Cipher.ENCRYPT_MODE, key);
    c.doFinal(data,0,data.length,ciphertext,0);
    where byte[] data = "1234567890".getBytes();
    I get no errors during this process.
    Now, when I try to decrypt the string, I get a padding error as follows:
    javax.crypto.BadPaddingException: Data must start with zero
    The decode is done on a server.
    I tried getting an instance of the cipher with RSA/ECB/NoPadding and this time the decrypt gives junk.
    Question 2: The SATSA example online at http://java.sun.com/j2me/docs/satsa-dg/AppD.html
    has a public key embedded as a byte array. They haven't explained how
    this key is generated. Does someone know?
    Question 3: Suppose, I can get the modulus and exponent of the public key is there any way I can convert it to X509EncodedKeySpec so that I can
    use the APIs in SATSA?
    Thanks in advance for your help. I have been trying to solve this for a lot of time and any help will be greatly appreciated.

    Just wanted to add my code:
    public class test2 {
         public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, ShortBufferException {
              // TODO Auto-generated method stub
              byte [] data = "012345678901234567890123456789ab".getBytes();
              Base64 base64 = new Base64();
    /*public key generated by
              byte [] mypublickey = base64.decode("publickey in PEM format");
              byte [] ciphertext = new byte[128];
              X509EncodedKeySpec test = new X509EncodedKeySpec(mypublickey);
              byte [] myprivatekey = base64.decode("privatekey in pkcs8format");
    KeyFactory rsakeyfac = KeyFactory.getInstance("RSA");
              PublicKey pubkey = rsakeyfac.generatePublic(test);
              Cipher c1 = Cipher.getInstance("RSA");
              c1.init(Cipher.ENCRYPT_MODE, pubkey);
              c1.doFinal(data, 0,data.length, ciphertext);
              PKCS8EncodedKeySpec pks2 = new PKCS8EncodedKeySpec(myprivatekey);
              RSAPrivateCrtKey privkey = (RSAPrivateCrtKey)rsakeyfac.generatePrivate(pks2);
              Cipher c2 = Cipher.getInstance("RSA");
              c2.init(Cipher.DECRYPT_MODE, privkey);
              byte [] decrypteddata = c2.doFinal(ciphertext);
              System.out.println("Decrypted String is:"+new String(decrypteddata).trim());
    Error that I get is:
    Exception in thread "main" javax.crypto.BadPaddingException: Data must start with zero
         at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
         at sun.security.rsa.RSAPadding.unpad(Unknown Source)
         at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
         at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
         at javax.crypto.Cipher.doFinal(DashoA13*..)

  • Have a problem when encrypt by RSA !!!

    I have a method
    public static byte[] EncryptByPublicKey(byte[] text, PublicKey key) {
            //byte[] encryptText = null;
            try {
                Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                cipher.init(Cipher.ENCRYPT_MODE, key);
                return cipher.doFinal(text);
            catch (Exception e){
                System.out.println("Err " + e.toString());
            return null;
        }I write a class test this method
    public static void main(String[] args){
            PublicKey pub = ReadPublicKey("publicReceiver.k");
            String message = "abc";
            String encryptText =
                        new String(EncryptByPublicKey(message.getBytes(), pub));
            System.out.println(encryptText);
        }when I execute the minutes each are different results for each.
    help me please, thanks a lot of

    PKCS1 padding in encryption mode uses random bytes for the padding so you should pretty much always get a different resultant encrypted result.
    Note - the bytes of the ciphertext should never be turned into readable text using new String(ciphertext) since one cannot guarantee that all bytes and byte sequences are valid for your default character encoding. Use Base64 or Hex encoding.

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

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

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

  • Problem with RSA/AES and the wrapped Key

    Hallo!
    For a server-client communications, I would like to use a hybrid encryption.
    For this I create an object of a serializable class that contains several properties, including the data that are to be transferred from A to B (Object, encrypted by AES), and the AES key, but wrapped by RSA (byte []).
    My basic problem is, that if I send the wrapped key, I get at the destination another byte array and thus the key can not be decoded:
    java.security.InvalidKeyException: Invalid AES key length: 256 bytes
    When I look at the string representation of the byte array before sending and immediate after receiving, the byte arrays are diffrent. Why?
    Extract from the encrypt method:
    TransportObject obj = new TransportObject();
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        SecureRandom random = new SecureRandom();
        keygen.init(random);
        Key key = keygen.generateKey();
        Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] wrappedKey = cipher.wrap(key);
    // Here I put the byte array in the object to be transmitted
        obj.setKey(wrappedKey);Extract from the decrypt method:
    / / Here I read the byte array from the received object
    byte[] wrappedKey = obj.getKey();
    Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
    cipher.init(Cipher.UNWRAP_MODE, privateKey);
    Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);Here is the class that is serialized:
    import java.io.Serializable;
    public class TransportObject implements Serializable {
        private static final long serialVersionUID = 5044061539587999682L;
        private byte[] key;
        private String type;
        private byte[] data;
        public static final int STRING = 1;
        public static final int INT = 2;
        public static final int CHAR = 3;
        public TransportObject() {}
        public TransportObject(byte[] key, String type, byte[] data) {
            this.key = key;
            this.type = type;
            this.data = data;
        public byte[] getKey() {
            return key;
        public void setKey(byte[] key) {
            this.key = key;
    }Sending is done via:
    TransportObject obj = rsa.encrypt(objectToSend, keys.getPublicKey());
    ObjectOutputStream os =
        new ObjectOutputStream(socket.getOutputStream());
    os.writeObject(obj);
    os.flush();Receiving via
    ois = new ObjectInputStream(
        new BufferedInputStream(socket.getInputStream()));
    TransportObject obj = (TransportObject) ois.readObject();
    Object receivedObject = rsa.decrypt(obj, keys.getPrivateKey());Somehow, I hang down here.
    Do I overlook something? Do I have an error in reasoning?
    Thanks for any help!
    Best regards
    Sebastian Gohres
    Edited by: Spencer82 on Aug 7, 2010 9:06 AM
    Edited by: Spencer82 on Aug 7, 2010 9:08 AM

    Do I overlook something? Do I have an error in reasoning?I think at least 2.
    1. Don't do this. The general problem has been solved. The solution is called TLS, and Java provides a API called the JSSE for you to use.
    2.If you insist on rolling your own, don't specify NoPadding. Use PKCS1Padding. If you are going to use NoPadding, then you must provide your own padding scheme, which you have not.

  • No luck with RSA and existing cert

    I want to encrypt data in my software, data which will be sent to me by the user, in such a way that only I can decrypt it. This seems to call for asymmetric encryption (only the public key would be embedded in the software), so I am trying to use RSA.
    Specifically I am trying to encrypt and decrypt data using the key pairs found in a cert that we bought from a cert authority. The cert says that key is a "Sun RSA public key, 1024 bits". In the following test, I encrypt using the cert's public key and decrypt using the same, for want of a method to return the private key but the results are the same if I initialize the cipher for decryption with the cert itself (which presumably contains the private key).
            Key key = cert.getPublicKey();
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] enc = cipher.doFinal(test.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] dec = cipher.doFinal(enc);but at the decyrption stage I get the following error:
    Exception in thread "main" javax.crypto.BadPaddingException: Data must start with zero.which I don't know what to make of. It seems to me that I am following the (rather scant) instructions to the letter. If I specify "RSA/ECB/NoPadding" as the transformation I don't get the above error but the roundtrip fails to recreate the original string.
    Furthermore, as I said before, I wanted to use public key encryption because I must include the encryption key in the software and I do not want it to be sufficient to decrypt the cipher. I was hoping that with RSA you'd encrypt using the public key but that you'd need either the secret key or the whole cert to decrypt. However the Javadocs do not say so explicitely and I am left unsure as to how this works exactly. Can anyone shed some light?

    I agree, the documentation is inadequate. Have you also looked at the JCE reference (http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html)? This expands a lot on the javadocs for the classes. It might also help to learn more about cryptography; one book that others recommend is "Practical Cryptography" by Ferguson and Schneier.
    I think the one key misunderstanding you have is what is in a certificate. A certificate contains only the public key, some information about the identity of the owner of the private key, and a digital signature over this public key and identifying information. The private key is not in the certificate! Nor should it be. If it were, it would no longer be private and the security of the system would fall apart.
    The location of the private key depends entirely on the application that created the key pair. java's keytool, for example, stores the private key in a password protected file.
    The error you are seeing makes sense once you understand that , for an RSA cipher, the type of key, public or private, as well as the mode Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE, determine the interpretation of the subsequent update or doFinal method calls.
    Thus in your example, your first call to cipher.doFinal gives the RSA encryption of the data, which is what you wanted. Your second, however, attempts to decrypt this encrypted data with the public key, which makes no sense in this context. It checks to see if the result is has the proper padding, which it does not. If you tell it to assume no padding, you won't get an exception but the result still won't make any sense. You need to init the cipher with the private key for the second part.

  • RSA decryption Error: Data must start with zero

    Because of some reasons, I tried to use RSA as a block cipher to encrypt/decrypt a large file. When I debug my program, there some errors are shown as below:
    javax.crypto.BadPaddingException: Data must start with zero
         at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
         at sun.security.rsa.RSAPadding.unpad(Unknown Source)
         at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
         at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:394)
         at javax.crypto.Cipher.doFinal(Cipher.java:2299)
         at RSA.RRSSA.main(RRSSA.java:114)
    From breakpoint, I think the problem is the decrypt operation, and Cipher.doFinal() can not be operated correctly.
    I searched this problem from google, many people met the same problem with me, but most of them didn't got an answer.
    The source code is :
    Key generation:
    package RSA;
    import java.io.FileOutputStream;
    import java.io.ObjectOutputStream;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    public class GenKey {
          * @param args
                     * @author tang
         public static void main(String[] args) {
              // TODO Auto-generated method stub
                 try {
                      KeyPairGenerator KPG = KeyPairGenerator.getInstance("RSA");
                      KPG.initialize(1024);
                      KeyPair KP=KPG.genKeyPair();
                      PublicKey pbKey=KP.getPublic();
                      PrivateKey prKey=KP.getPrivate();
                      //byte[] publickey = decryptBASE64(pbKey);
                      //save public key
                      FileOutputStream out=new FileOutputStream("RSAPublic.dat");
                      ObjectOutputStream fileOut=new ObjectOutputStream(out);
                      fileOut.writeObject(pbKey);
                      //save private key
                          FileOutputStream outPrivate=new FileOutputStream("RSAPrivate.dat");
                      ObjectOutputStream privateOut=new ObjectOutputStream(outPrivate);
                                 privateOut.writeObject(prKey)
         }Encrypte / Decrypt
    package RSA;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.security.Key;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.crypto.Cipher;
    //import sun.misc.BASE64Decoder;
    //import sun.misc.BASE64Encoder;
    public class RRSSA {
          * @param args
         public static void main(String[] argv) {
              // TODO Auto-generated method stub
                //File used to encrypt/decrypt
                 String dataFileName = argv[0];
                 //encrypt/decrypt: operation mode
                 String opMode = argv[1];
                 String keyFileName = null;
                 //Key file
                 if (opMode.equalsIgnoreCase("encrypt")) {
                 keyFileName = "RSAPublic.dat";
                 } else {
                 keyFileName = "RSAPrivate.dat";
                 try {
                 FileInputStream keyFIS = new FileInputStream(keyFileName);
                 ObjectInputStream OIS = new ObjectInputStream(keyFIS);
                 Key key = (Key) OIS.readObject();
                 Cipher cp = Cipher.getInstance("RSA/ECB/PKCS1Padding");//
                 if (opMode.equalsIgnoreCase("encrypt")) {
                 cp.init(Cipher.ENCRYPT_MODE, key);
                 } else if (opMode.equalsIgnoreCase("decrypt")) {
                 cp.init(Cipher.DECRYPT_MODE, key);
                 } else {
                 return;
                 FileInputStream dataFIS = new FileInputStream(dataFileName);
                 int size = dataFIS.available();
                 byte[] encryptByte = new byte[size];
                 dataFIS.read(encryptByte);
                 if (opMode.equalsIgnoreCase("encrypt")) {
                 FileOutputStream FOS = new FileOutputStream("cipher.txt");
                 //RSA Block size
                 //int blockSize = cp.getBlockSize();
                 int blockSize = 64 ;
                 int outputBlockSize = cp.getOutputSize(encryptByte.length);
                 /*if (blockSize == 0)
                      System.out.println("BLOCK SIZE ERROR!");       
                 }else
                 int leavedSize = encryptByte.length % blockSize;
                 int blocksNum = leavedSize == 0 ? encryptByte.length / blockSize
                 : encryptByte.length / blockSize + 1;
                 byte[] cipherData = new byte[outputBlockSize*blocksNum];
                 //encrypt each block
                 for (int i = 0; i < blocksNum; i++) {
                 if ((encryptByte.length - i * blockSize) > blockSize) {
                 cp.doFinal(encryptByte, i * blockSize, blockSize, cipherData, i * outputBlockSize);
                 } else {
                 cp.doFinal(encryptByte, i * blockSize, encryptByte.length - i * blockSize, cipherData, i * outputBlockSize);
                 //byte[] cipherData = cp.doFinal(encryptByte);
                 //BASE64Encoder encoder = new BASE64Encoder();
                 //String encryptedData = encoder.encode(cipherData);
                 //cipherData = encryptedData.getBytes();
                 FOS.write(cipherData);
                 FOS.close();
                 } else {
                FileOutputStream FOS = new FileOutputStream("plaintext.txt");
                 //int blockSize = cp.getBlockSize();
                 int blockSize = 64;
                 //int j = 0;
                 //BASE64Decoder decoder = new BASE64Decoder();
                 //String encryptedData = convert(encryptByte);
                 //encryptByte = decoder.decodeBuffer(encryptedData);
                 int outputBlockSize = cp.getOutputSize(encryptByte.length);
                 int leavedSize = encryptByte.length % blockSize;
                 int blocksNum = leavedSize == 0 ? encryptByte.length / blockSize
                           : encryptByte.length / blockSize + 1;
                 byte[] plaintextData = new byte[outputBlockSize*blocksNum];
                 for (int j = 0; j < blocksNum; j++) {
                 if ((encryptByte.length - j * blockSize) > blockSize) {
                      cp.doFinal(encryptByte, j * blockSize, blockSize, plaintextData, j * outputBlockSize);
                      } else {
                      cp.doFinal(encryptByte, j * blockSize, encryptByte.length - j * blockSize, plaintextData, j * outputBlockSize);
                 FOS.write(plaintextData);
                 //FOS.write(cp.doFinal(encryptByte));
                 FOS.close();
    }Edited by: sabre150 on Aug 3, 2012 6:43 AM
    Moderator action : added [ code] tags so as to make the code readable. Please do this yourself in the future.
    Edited by: 949003 on 2012-8-3 上午5:31

    1) Why are you not closing the streams when writing the keys to the file?
    2) Each block of RSA encrypted data has size equal to the key modulus (in bytes). This means that for a key size of 1024 bits you need to read 128 bytes and not 64 bytes at a time when decrypting ( this is probably the cause of your 'Data must start with zero exception'). Since the input block size depends on the key modulus you cannot hard code this. Note - PKCS1 padding has at least 11 bytes of padding so on encrypting one can process a maximum of the key modulus in bytes less 11. Currently you have hard coded the encryption block at 64 bytes which is OK for your 1024 bits keys but will fail for keys of modulus less than about 936 bits.
    3) int size = dataFIS.available(); is not a reliable way to get the size of an input stream. If you check the Javadoc for InputStream.available() you will see that it returns the number of bytes that can be read without blocking and not the stream size.
    4) InputStream.read(byte[]) does not guarantee to read all the bytes and returns the number of bytes actually read. This means that your code to read the content of the file into an array may fail. Again check the Javadoc. To be safe you should used DataInputStream.readFully() to read a block of bytes.
    5) Reading the whole of the cleartext or ciphertext file into memory does not scale and with very large files you will run out of memory. There is no need to do this since you can use a "read a block, write the transformed block" approach.
    RSA is a very very very slow algorithm and it is not normal to encrypt the whole of a file using it. The standard approach is to perform the encryption of the file content using a symmetric algorithm such as AES using a random session key and use RSA to encrypt the session key. One then writes to the ciphertext file the RSA encrypted session key followed by the symmetric encrypted data. To make it more secure one should actually follow the extended procedure outlined in section 13.6 of Practical Cryptography by Ferguson and Schneier.

  • How to make already written Encryption code in JDK 1.3  work in JDK 1.4

    Hi,
    We are using JCE to encrypt a number.The following code was written in JDK 1.3 and is now on the Live site.
              byte[] publicKeyBytes =new BigInteger("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", Character.MAX_RADIX).toByteArray();
         EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
    PublicKey key = KeyFactory.getInstance("RSA").generatePublic(spec);
    // Create Cipher
    Cipher desCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
         desCipher.init(Cipher.ENCRYPT_MODE, key);
    We are now migrating to JDK 1.4. When I tried to execute the above lines in JDK 1.4, it came back with the following error
    "Cannot find any provider supporting RSA/ECB/PKCS1Padding"
    Then I downloaded and copied over the iaik_jce_full.jar in \j2sdk1.4.1_05\jre\lib\ext\ folder
    and added the following entry in \j2sdk1.4.1_05\jre\lib\security\java.policy
    security.provider.1=iaik.security.provider.IAIK
    Now, it has started giving me the following error:
    java.lang.ExceptionInInitializerError
         at javax.crypto.Cipher.a(DashoA6275)
         at javax.crypto.Cipher.getInstance(DashoA6275)
    Caused by: java.lang.SecurityException: Cannot set up certs for trusted CAs
         at javax.crypto.SunJCE_b.(DashoA6275)
         ... 39 more
    Caused by: java.lang.UnsupportedOperationException
         at java.security.cert.CertificateFactorySpi.engineGenerateCertPath(CertificateFactorySpi.java:155)
         at java.security.cert.CertificateFactory.generateCertPath(CertificateFactory.java:470)
         at javax.crypto.SunJCE_d.a(DashoA6275)
         at javax.crypto.SunJCE_d.a(DashoA6275)
         at javax.crypto.SunJCE_b.i(DashoA6275)
         at javax.crypto.SunJCE_b.h(DashoA6275)
         at javax.crypto.SunJCE_v.run(DashoA6275)
         at java.security.AccessController.doPrivileged(Native Method)
         ... 40 more
    Can someone tell me where I am wrong and please write the steps I need to follow to make the above code work in JDK 1.4
    Bye

    in java 1.4 JSSE is default provider
    may be u need to use another provider (SunJCE)
    see JSSE :
    Note for People Implementing Providers
    The transformation strings used when SunJSSE calls Cipher.getInstance() are "RSA/ECB/PKCS1Padding", "RC4", "DES/CBC/NoPadding", and "DESede/CBC/NoPadding". For further information on the Cipher class and transformation strings see the JCE Reference Guide.
    PS u didnot need load jce. it is into j2se 1.4

  • MD5 and RSA - Slow performance  - Help / Views Required

    Hi,
    I am facing a problem while signing a message.The
    scenario is:
    I have to create 20,000 messages to be sent to
    clients. I am encrypting the message using MD5 and
    RSA.
    But when i am encrypting via RSA it takes about 20
    mins to encrypt the 20k messages.I dont know why its
    taking so much time. I have max 4-5 mins to manipulate
    and send messages. The sample code is as follows:
    ur earliest help will be quite helpful.
    Thanks in advance
    Hassan
    ************** Source Code ****************
    import java.io.IOException;
    import java.math.BigInteger;
    import java.security.KeyFactory;
    import java.security.MessageDigest;
    import java.security.Signature;
    import java.security.PrivateKey;
    import java.security.spec.RSAPrivateKeySpec;
    import org.apache.log4j.Logger;
    public class Signer {
    ******************************************

    Hi Sabre,
    I have compiled the simple code from JCE tutorial for DES. The output text it is showing is different than input text.
    Is there any problem going on in tutorial's example ?
    Regards
    Hamid
    ******** output **************
    the original cleartext is: [B@13a328f
    the encrypted text is: [B@337838
    the final cleartext is: [B@119cca4
    ******** Code ************
    public class jCypher {
    private static Cipher desCipher = null;
    public static void main (String[] args) throws NoSuchAlgorithmException,
    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,
    BadPaddingException, NoSuchPaddingException, Exception
    //Creating a Key Generator and Generating a Key
    //public static KeyGenerator getInstance(String algorithm);
    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    SecretKey desKey = keygen.generateKey();
    // Creating a Cipher
    // Cipher.getInstance(Transformation);     
    // c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");     
    desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    // Cipher.init(int opmode, Key key);
    desCipher.init(Cipher.ENCRYPT_MODE, desKey );
    // Cleartext
    byte[] cleartext = "This is small Text for testing".getBytes();
    System.out.println("the original cleartext is: " + cleartext.toString());
    // Encrypt the cleartext
    // encrypted or decrypted data in one step (single-part operation)
    // public byte[] doFinal(byte[] input);
    byte[] ciphertext = desCipher.doFinal(cleartext);
    System.out.println("the encrypted text is: " + ciphertext.toString());
    // Initialize the same cipher for decryption
    desCipher.init(Cipher.DECRYPT_MODE, desKey );
    // Decrypt the ciphertext
    byte[] cleartext1 = desCipher.doFinal(ciphertext);
    System.out.println("the final cleartext is: " + cleartext1.toString());
    } // End main()
    }

Maybe you are looking for

  • How to capture Button Click in OAF

    Hi All, I have created a button "TestButton" using personalization. On the click of this button, a new page "TestPG" opens. But i have to pass a few parameters from the old page to the new page. How do i capture this button click event in the CO so t

  • ICal month view won't show some of my appointments.

    Hello guys! I've updated do Lion and bought an iPod touch 4g. Everything is working fine, except for the month view on my Mac Book Pro, some of my appointments won't show up for me. The appear on Day view and Week view. Any ideas?

  • Delivery Completion Indicator- Control?

    Hi all,    In our organization we have defined the release strategy in such a way that, we are having 8 release codes in a release strategy,, by means of release indicator blocked and released,,,once the PO was released bythe initial hierarchy releas

  • Is there a way to capture the position of the scrollbar?

    On this form that i am using, I am capturing where the cursor is by using temp_value := :System.Cursor_Record to find out what record it is and then when the timer expires i am asking it to go back to that captured record by GO_RECORD(temp_value ) wh

  • How to synchronize Sql Server when Oracle table has trigger

    Hi I have a trigger which will update/insert the data into a Oracle table. I have an interface which normally moves the data from Oracle table to SQL Server table. Is there any way which will update/insert the data into SQL Server table whenever any