Using base64 in applet

Hey,
I want to use the base64 encoder in my applet but I get faults.
I think the problem is that he doesn't recognize the BASE64Encoder.
This is my code:
//some other imports
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.*;
import java.security.*;
// This is for BASE64 encoding and decoding
import sun.misc.*;
public class Demo4 extends Applet{
//some code
public String encrypt(String pass, String plaintext)
          throws Exception
          char[] password = pass.toCharArray();
          byte[] ciphertext = plaintext.getBytes();
     //herkend BASE64Encoder niet
          BASE64Encoder encoder = new BASE64Encoder();
          String ciphertextString = encoder.encode(ciphertext);
          return encoder.encode(ciphertext);
This function I want to call in my html page using javascript.
Does anyone know what the problem can be?

Don't use the sun.misc.* classes. They are undocumented, subject to change, and may not be included with all distributions of Java.
There are many alternatives out there for Base64 encoding. I have written one:
http://ostermiller.org/utils/Base64.html
You can include it in your applet.
Stephen

Similar Messages

  • Can parport be used in a applet?

    I have been trying to get parport to read and write in an applet but have had no success. It works fine at the command line but when used in the applet it stops my applet program when it comes to executing the read function.
    My first idea was keep the parport read and write codes completely seperate from the applet in their own class file and then call the class file to be run. Is this at all possible?
    I have posted the code to see if i can make this clearer
    import parport.ParallelPort;
    class SimpleIO {
    public static void main ( String []args )
    ParallelPort lpt1 = new ParallelPort(0x378); // 0x378 is normally the base address for the LPT1 port
    int aByte;
    aByte = lpt1.read(); // read a byte from the port's STATUS pins
    System.out.println("Input from parallel port: " + aByte);
    aByte = aByte >> 2; // a simple and irrelevant operation
    lpt1.write(aByte); // write a byte to the port's DATA pins
    System.out.println("Output to port: " + aByte);
    //////////////This code above will be kept in its own java file called SIMPLEIO.java////////
    I then want to call and run this code from my applet java file. After some experimenting i think i have found out that you need the
    public static void main ( String []args ) line in the parport code in order for it work properly. What code would i use to call and run this code from the applet file
    Thx for reading my long post and thx to all who try and help me out

    My first idea was keep the parport read and write codes completely seperate from the applet in their
    own class file and then call the class file to be run. Is this at all possible?No. The problem is that applets run in what's called a sandbox which prevents them, and any classes called from them, from doing any local IO.
    This is essential for security, since a web page can run an applet without the user knowing about it, and it could get up to all kinds of mischief.
    You can digitally sign the applet, which will then ask the user for permission to run with reduced restrictions. A quick search of java/sun should turn up some instructions.

  • Is it possible to use JAXP in Applet? Really urgeng.

    I need to get String output from a DOM Document using JAXP in Applet. I want the entire XML document in one string .I write the code as following,but it doesn't work. Would you help me to point out the mistake I made in it?
    Any help would be appreciated,
    Thanks.
    import java.awt.*;
    import javax.swing.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.*;
    import javax.xml.transform.dom.DOMSource;
    import java.io.*;
    import java.io.IOException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import java.util.*;
    public class XMLTest extends JApplet {
         String str;
         public void init()
         str="hello";
    try
    DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
    DocumentBuilder db =factory.newDocumentBuilder();
    Document m_dDoc = db.newDocument();
    Element e1=m_dDoc.createElement("first");
    Text tx;
    tx=m_dDoc.createTextNode("hi");
    e1.appendChild(tx);
    m_dDoc.appendChild(e1);
    DOMSource doms = new DOMSource(m_dDoc);
    Writer out = new StringWriter();
    StreamResult result = new StreamResult(out);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();//wrong
    transformer.transform(doms,result);
    str=result.toString();
    catch(Exception e)
    e.printStackTrace();
         public void paint(Graphics g)
              g.drawString(str, 50, 60 );
    }

    The problem is that using the transformer in an applet results in the exception:
    The exception is as following:
    org.apache.xml.utils.WrappedRuntimeException: Output method is xml could not loa
    d output_xml.properties (check CLASSPATH)
    at org.apache.xalan.templates.OutputProperties.getDefaultMethodPropertie
    s(OutputProperties.java:364)
    at org.apache.xalan.templates.OutputProperties.<init>(OutputProperties.j
    ava:130)
    at org.apache.xalan.transformer.TransformerIdentityImpl.<init>(Transform
    erIdentityImpl.java:104)
    at org.apache.xalan.processor.TransformerFactoryImpl.newTransformer(Tran
    sformerFactoryImpl.java:804)
    at XMLTest.init(XMLTest.java:36)
    at sun.applet.AppletPanel.run(AppletPanel.java:341)
    at java.lang.Thread.run(Thread.java:536)
    I am still unclear to the cause, when I create a copy of the output_xml.properties file and put it somewhere in your classpathe (I put mine in a jar that the applet loads) you get:
    java.lang.ExceptionInInitializerError
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:140)
         at org.apache.xalan.serialize.SerializerFactory.getSerializer(SerializerFactory.java:131)
         at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(TransformerIdentityImpl.java:232)
         at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:296)
         at com.thalesgroup.mss.infrastructure.xml.SOAPMessage.domDocToString(SOAPMessage.java:180)
         at com.thalesgroup.mss.applets.filemanager.XmlMessages.getFileList(XmlMessages.java:246)
         at com.thalesgroup.mss.applets.filemanager.FileManagerFrame.getFileList(FileManagerFrame.java:575)
         at com.thalesgroup.mss.applets.filemanager.FileManagerFrame.access$2(FileManagerFrame.java:29)
         at com.thalesgroup.mss.applets.filemanager.FileManagerFrame$fileList.run(FileManagerFrame.java:847)
    Caused by: java.lang.RuntimeException: The resource [ XMLEntities.res ] could not load: java.net.MalformedURLException: no protocol: XMLEntities.res
    XMLEntities.res      java.net.MalformedURLException: no protocol: XMLEntities.res
         at org.apache.xalan.serialize.CharInfo.<init>(CharInfo.java:202)
         at org.apache.xalan.serialize.SerializerToXML.<clinit>(SerializerToXML.java:292)
         ... 10 more
    Which leads me to some questions:
    What is XMLEntities.res, and how do I get one?
    Does anyone know which version of Xalan and JAXP comes with J2SE 1.4.1?
    Why the package "org.apache.xalan.Version" is not in the J2SE 1.4.1 release (and should it be?)

  • Can I Use Jce in applet

    Hi all,
    Thanks for everybody first if you look at my question and try to help me to find out the problem.
    I need to write a applet which can let people to use
    the jce's des function to encipher the user's password and
    id from the homepage.
    I write a applet already. It work fine as a application.
    But it doesn't work when I run it as a applet. Does the problem come from the security problem because I need
    to Load a sun_jce provider in a clien machine ?
    Can I use JCE in applet ?
    If it is ok to use jce in developing applet do I need to sign the applet before run it in web and which file I need to sign.
    Btw, I use the archive tag in html file to make user get the whole jce jar file. does it Ok.
    Followin is my source code
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.security.*;
    import sun.misc.*;
    import java.applet.*;
    import java.awt.*;
    public class DesApplet extends Applet{
         public static void main(String[] arg) throws Exception{
              DesApplet des = new DesApplet();
              des.CallDes();
         public void init(){
              CallDes();
         public void paint(Graphics g){
         public CallDes(){
              Cipher desCipher;
              int i;                              
              try{
                   Security.addProvider(new com.sun.crypto.provider.SunJCE());
                   KeyGenerator keygen = KeyGenerator.getInstance("DES");
                   SecretKey desKey = new SecretKeySpec("11111111".getBytes(),"DES");
                   System.out.println("Hello");
                   desCipher = Cipher.getInstance("DES/ECB/NoPadding");
                   desCipher.init(Cipher.ENCRYPT_MODE,desKey);
                   byte[] cleartext = "00000000".getBytes();
                   String value = convert_int_to_hex(cleartext,8);
                   System.out.println("cleartext is:"+value);
                   byte[] ciphertext = desCipher.doFinal(cleartext);
                   value = convert_int_to_hex(ciphertext,8);
                   System.out.println("ciphertext is:"+value);
                   desCipher.init(Cipher.DECRYPT_MODE,desKey);
                   byte[] cleartext1 = desCipher.doFinal(ciphertext);;
                   value = convert_int_to_hex(cleartext1,8);
                   System.out.println("cleartext1 is:"+value);
              }catch(Exception e){System.err.println(e);}
         public String convert_int_to_hex(byte[] value, int len) {
         int i;
         int j;
         byte tmp;
         byte[] temp = new byte[len*2];
         char[] chars = new char[len*2];
         String result = new String();
         for (i=0; i<len; i++)
         if (value[i] < 0)
         temp[i*2] = (byte)((value[i] & 0xF0) >>> 4);
         temp[i*2+1] = (byte)(value[i] & 0x0F);
         else
         temp[i*2] = (byte)(value[i] / 16);
         temp[i*2+1] = (byte)(value[i] % 16);
         for (i=0; i<len*2; i++)
         if (temp[i] > 9)
         chars[i] = (char)(temp[i] - 10 + 65);
         else
         chars[i] = (char)(temp[i] + 48);
         result = result.concat(result.valueOf(chars));
         return result;

    I have a server and a client.
    Server has jdk1.4. client is an applet. I need to encrypt the username and password that are sent from client to the server.
    I am able to encrypt and decrypt using JCE's DES on server side, since jdk1.4 has JCE provider installed by default. Since the applet may be running on any browser which may not have JCE supported. Is it possible for me to send the JCE jar file along with the applet and somehow enable the client applet to encrypt the user name and password and send to server.
    Thanks a lot,
    Gagan.

  • Using bc4j with applets

    Hi,
    I was wondering if you have any tips on using bc4j in applets. The 2 biggest problems I'm having is the jar size of the applet after all libs are included
    (4MB+) and the fact that I can't use XDK, JNDI, BC4J and some other libs from applets unless I sign them or change the policy file at each client using the applets.
    I really think all the calls to System.getProperties(), etc. should be placed inside try catch blocks to catch the security exceptions raised by xdk, RMIInitialContextFactory, etc. and handled using
    defaults for properties... it'd be even better if these properties could be set in another way as well.
    Thanks in advance,
    Leonardo Bueno

    FYI... my environment is:
    Oracle9iAS (9.0.3.0.0)
    JDeveloper (9.0.3.4)

  • Using javaagents with applets

    Is it possible to use javaagents with applets?
    If it is, how?

    FYI... my environment is:
    Oracle9iAS (9.0.3.0.0)
    JDeveloper (9.0.3.4)

  • Why isn't System.exit(0) used from an Applet

    I am trying to figure out why the System.exit(0) method isn't used for an applet. Is it because an applet isn't an application (which is why the public static void main(String args[]))?
    I have noticed when if I include System.exit(0) I will get an compilation error.
    Is there someplace in the Java Tutorial that explains this?
    thanks

    You can put it in, but if you run it in a browser, it
    will kill the browser and all its windowsThat is if the applet is signed. I have also noticed this behaviour and I think it is pretty weird. It looks like a bug to me.

  • How to show an html page using JEditorPane in applet.

    I have never use jeditorpane with applet so i dont know how to show a html page.if you have some code or any example then please posted that.Thanks

    public class MyApplet extends JApplet{
        private JTextPane textPane = null;
        public void init(){
        HTMLEditorKit editorKit = new HTMLEditorKit();
        HTMLDocument  htmlDoc   = (HTMLDocument)editorKit.createDefaultDocument();
        textPane  = new JTextPane();
        textPane.setEditable(false);
        textPane.setEditorKit(editorKit);
        textPane.setContentType("text/html");
        textPane.setDocument(htmlDoc);
        Container c = getContentPane();
        c.add(new JScrollPane(textPane),    BorderLayout.CENTER);
        c.add(buttonPanel,                  BorderLayout.SOUTH);
        c.add(Box.createVerticalStrut(5),   BorderLayout.NORTH);     
        c.add(Box.createHorizontalStrut(5), BorderLayout.EAST);     
        c.add(Box.createHorizontalStrut(5), BorderLayout.WEST);
        public void setHtml(String html){
            // you should check the textpane's document to detrmine if there
            // is already text in there..if so, then clear the textpane text and then
            // set the new html...Note: JTextPane only show basic Html ..
            // not like a full blown browser
            textPane.setTextt(html);
            textPane.setCaretPosition(0);
    }

  • Using JMF with applet

    Hello,
    I've got an applet that consumes a lot of CPU. I'm studying to migrate this applet to a pda, but it's not enough cpu for it. I'm reading JMF docs and I decide to generate a movie with the output of an applet. �If it's possible? My idea is to create the movie on the server. I can modify my applet to avoid the use of the applet inheritance and then render the output to an standard movie format. After I will send the movie to the browser
    You can see the applet here. Click on View route 3D under the flash movie.
    http://www.tmb.net/vullanar/en_US/resultatcerca.jsp?tipusrepre=0&origenx=31514.420&origeny=82758.000&descripcioorigen=L1+-ARCDE+TRIOMF&destix=34704.550&destiy=87378.460&descripciodesti=L2+-ARTIGUES-SANTADRI%C0&tipustransport=0&numtransbords=2&tempscaminant=20&velocitatcaminant=1&tipushora=1&dia=27&mes=05&hora=12&minut=22&idioma=en_US&operador=TMB&poblacioorigen=1&poblaciodesti=1
    Thanks in advance,
    David B.

    passionforjava2 wrote:
    ...I have issues with applet unable to transmit voice using JMF. i know it is a security issue. As the error on the console says
    java.lang.RuntimeException: No permission to capture from applets
    Error : Couldn't create DataSourceWhen JMF is installed, it generally offers a checkbox to allow or deny 'capture in applet'. By default it is not checked, and if the user goes with that recommendation, I am not sure that anything will overrule that.
    In a folder iPhone/myphone/What is the URL where we can visit this applet?
    .. i have applet embedded html file along with .jar files with required classed and applet signed. Are you prompted to trust the digitally signed code? You can see the dialog I mean by visiting the applet linked from [http://pscode.org/test/docload/].
    ..Along with that .jar i do have jmf.jar and java.policy.applet file and jmf.properties file . Forget the policy files, they are a waste of time, and completely impractical for end users.

  • Using a java applet as form

    hi there,
    I'm new to programming applets (but not new to java and gui programming).
    Here's my question:
    I would like to use a java applet with a textfield as form input. is this possible?
    I see some several advantages over using standard html textfields and java script. (f.e.: I can set the cursor to any position after changing the text in the field).
    I'm thinking on a solution by my own. Would it be possible to use a java script method to access a property from the applet? so I could use a combination of java applet, html and java script. On the onClick() event I read the actual value from the applet and do some normal post request. Any better suggestions?
    thx
    soa

    I want to write the textfield in java. So I use the applet as form.
    What would be your suggestion?
    Write an applet with an textfield and and getValue() method? So I could create a normal html button and use javascript to write a method wich acces this getmethod. So I could register this method to the onClick() event.

  • Encoding using BASE64

    Hi All,
    i required some sample code for encoding using BASE64 encoding.
    can any one please help in doing the code for encoding a text.
    Thanks in advance.

    There are quite a few examples of Base64 encoders and decoders on the web. I didn't see any written in Obj-C or coded with a Cocoa interface, but perhaps you might find one if you spend some time searching.
    The example code you have is pure ANSI C, which means it can be added to any Xcode iPhone project as a separate file, wrapped into its own Obj-C class, or simply added to an existing class implementation. Since you only need to encode a short string, you'll only need the encode() and encodeblock() functions, along with the cb64[] array. encode() is expecting stdio FILE pointers for input and output, so you'll want to replace those parameters and the code which reads and writes from/to those streams with code that reads a C string (obtained from a NSString with UTF-8 encoding) and returns a NSData object.
    If you're not a C programmer, you will need to get some help from one, but it should be an easy job. Of course you should review the MIT license to make sure you're in compliance. But the reason I selected this example for you is that it's so well documented, it will teach you everything you need to know to write your own code from scratch if you need to.
    \- Ray
    p.s.: Here's some Cocoa code I found for you: [http://www.cocoadev.com/index.pl?BaseSixtyFour] - R

  • Do I need to use a Signed Applet ?

    I need to create a web application that calls methods in an existing DLL on client machines. This DLL will commincate with the serial port to send and receive info.
    Do I need to use a signed Applet do do this or is there another way?

    and by the way the DLL is WIN32 written in C... and there is no way to modify it... it is to be used as is..

  • How to update content of a file on server using a Java Applet?

    Hi,
    I'm new to Java, and I have a task now to overwrite a text file on a server using an applet. I have written a piece of code which compiles but doesn't work. Can you please take a look at the code or give me another way to do it?
    Thanks.
    Code:
    import java.applet.Applet;
    import java.io.*;
    import java.net.*;
    public class test2 extends Applet{
    public void init() {
    StringBuffer buf = new StringBuffer();
    try {
         String output = "this is some string";
         URL aUrl = new URL (getCodeBase().toString() + "test.txt");
         System.out.println(aUrl);
         URLConnection con = aUrl.openConnection();
         con.setDoOutput(true);
         PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(con.getOutputStream())));
         out.println(output);
         out.close();
    catch (MalformedURLException mue) {
         System.out.println("improper url");
         mue.printStackTrace();
    catch (IOException e) {
         System.out.println("io exception");
         e.printStackTrace();
    }

    Ram.ViSolve wrote:
    869975 wrote:
    Thanks. I knew there would be a security issue, but I do not have sufficient knowledge to get around it. If you have a reference how to configure a server please post it here.You need to create Signed Applet. Because normally applets have some restriction to access the files in the client machine. Signed applets overrides the restriction.
    To know more, Read [url http://192.9.162.55/developer/onlineTraining/Programming/JDCBook/signed.html]Signed Applet
    No. Our OP wants to write to the server, not to the client! And to achieve this from an applet, you don't need it signed, iff the server is the machine from where the applet was downloaded in the first place. You only need to use a mechanism that allows you to write to servers, which HTTP is not. FTP, on the other hand, if setup properly can do it. So instead of trying to write using an HttpURLConnection (OP's attempt), you would use an FTP client library. FTP here is just an example and probably not the best way. Another option is to use some servlet or PHP or ASP on the server side and the applet will sumbmit the changes to that code on the server, which in turn will write to the file. The idea is that you need some 'partner code' on the server, be it the FTP server or the servlet/PHP/ASP code. None of this requires the applet to be signed.

  • Since Firefox 4, I can get a background image to work using base64 encoded, but not a local file, this worked in Firefox 3, how do I resolve this.

    Using either of the 4 examples shown below, to have a background image display inside about:blank worked in Firefox 3.x (using Stylish add-on), however since Firefox 4, only using the base64 encoded version of images works. Is there any way to fix this so I don't have to encode every image I wish to use? Encoding the image makes the stylish file absolutely huge, & a real pain to keep encoding whenever I want to change the image.
    body:empty { background: url("resource:/res/images/OnFire.jpg")
    body { background-image: url("resource:/res/images/OnFire.jpg")
    body:empty { background:url("data:
    body { background-image: url("data:
    I've also previously disabled most of the add-ons, except for Status-4-Evar, Stylish, & Firebug, in an attempt to see if something else was interfering, but no change.
    I can supply a copy of the previously working (FF 3.x) code to some of the about:blank styles if needed for testing purposes.

    Type '''about:addons'''<enter> in the address bar to open the '''Add-ons Manager.'''
    Hot key; '''<Control>''(Mac:<Command>)'' <Shift> A)'''
    On the left side of the page, select '''Plugins.'''
    Is it listed here? Select '''Disable.'''

  • Flash Builder 4.5 SOAP call for images using Base64 Encoding

    I am trying to load some image meta data in a flash builder mobile application by making a SOAP call to .Net service. I am able to test the web service successfully using a .Net console application. However when I make the call from flash builder mobile client I get a null result. What am I doing wrong? I am using SOAP 1.1 ByteArray didn't work for Flash builder. So converted the ByteArray to Base64 format and tried to obtain result that way. Both ways worked from a .Net Client but not working from Flash mobile.
    Here is the code
    <fx:Script>
            <![CDATA[          
                import mx.graphics.ImageSnapshot;
                import mx.graphics.codec.JPEGEncoder;
                import mx.graphics.codec.PNGEncoder;
                import mx.rpc.AsyncToken;
                import mx.utils.Base64Encoder;         
                import services.exifimagemetadata1.ExifImageMetaData1;         
                import spark.components.Image;     
                public var metaData:ExifImageMetaData1 = new ExifImageMetaData1();         
                public var imageBytes:ByteArray = new ByteArray();
                public var gpsData:String;
        private function getBase64EncodedImage():String
                    var myEncoder:Base64Encoder = new Base64Encoder();
                    myEncoder.encodeBytes(getImageBytes());            
                    var image64BitText:String = myEncoder.toString();                          
                    return image64BitText;
        public function GetMetaDataFromExif():void{
                    var imageToken:AsyncToken = metaData.GetExifBase64Data(getBase64EncodedImage());               
                    gpsData = imageToken.result.toString();
                    metaResult.text = gpsData;
        protected function GetImageMetaDataFromExif(event:MouseEvent):void
                    GetMetaDataFromExif();         
            ]]>
        </fx:Script>
    <s:layout>
            <s:VerticalLayout>         
            </s:VerticalLayout>
        </s:layout>
        <s:HGroup>
            <s:Image id="test" width="130" height="140" source="@Embed(source='assets/p1000106.jpg')"/>
        </s:HGroup>
        <s:HGroup>
        <s:Label width="100" height="140" backgroundColor="Blue" click="GetImageMetaDataFromExif(event)">
            <s:text/>
        </s:Label>
        </s:HGroup>
        <s:HGroup>
            <s:Label id="metaResult" width="200" height="140" backgroundColor="yellow"/>           
        </s:HGroup>

    Hello everyone -
    Since I last posted an interesting update happened. I tested my  Flex application again, it is calling a Jetty Server that returns a JSON object, in different BROWSERS.  I disabled HTTPS for now, and the crossdomain.xml policy file is wide open for testing (ie. allowing every request to return data). So the app accessing the data using HTTP only. Browsers  -  IE, Opera, Firefox and Chrome. Each browser contained the SAME application, revision of the Flash Player (10.3.183.10 debugger for firefox, chrome, opera, safari PC; 11.0.1.129 consumer version in IE9,) take a look at the screen shot (safari not shown although the result was the same as IE and chrome)
    Note that Opera and Firefox returned successful values (i.e. successful JSON objects) using the same code generated from the Data Services Wizard. Chrome, IE and, Safari failed with an Internal error. So I am left wondering - WHY? Is it something with the Flash Player? the Browsers?  the Flex SDK? Any thoughts are appreciated. Again, the code is found in the original thread above.

Maybe you are looking for