.
Tampilkan postingan dengan label JavaScript. Tampilkan semua postingan
Tampilkan postingan dengan label JavaScript. Tampilkan semua postingan

Kamis, 09 Januari 2014

Creating a File Encryption App with JavaScript

 
Security and privacy are hot topics at the moment. This is an opportunity for us to take an introspective look into the way we approach security. It is all a matter of compromise – convenience versus total lock down. Today’s tutorial is an attempt to mix a bit of both.
The app we are going to build today is an experiment that will allow people to choose files from their computers and encrypt them client-side with a pass phrase. No server-side code will be necessary, and no information will be transferred between client and server. To make this possible we will use the HTML5 FileReader API, and a JavaScript encryption library - CryptoJS.
Note that the app doesn’t encrypt the actual file, but a copy of it, so you won’t lose the original. But before we start, here are a few issues and limitations:

Issues and limitations

The 1MB limit
If you play with the demo, you will notice that it doesn’t allow you to encrypt files larger than 1mb. I placed the limit, because the HTML5 download attribute, which I use to offer the encrypted file for download, doesn’t play well with large amounts of data. Otherwise it would cause the tab to crash in Chrome, and the entire browser to crash when using Firefox. The way around this would be to use the File System API and to write the actual binary data there, but it is supported only in Chrome for now. This is not an issue with the encryption speed (which is quite fast), but with offering the file for download.

What about HTTPS?
When it comes to encrypting data and securing information, people naturally expect the page to be loaded through HTTPS. In this case I believe it is not necessary, as apart from the initial download of the HTML and assets, no data is transferred between you and the server – everything is done client-side with JavaScript.  If this bothers you, you can just download the demo and open it directly from your computer.

How secure is it?
The library that I use - CryptoJS - is open source, so I believe it to be trustworthy. I use the AES algorithm from the collection, which is known to be secure. For best results, use a long pass phrase that is difficult to guess.

JavaScript File Encryption App
JavaScript File Encryption App

The HTML

The markup of the app consists of a regular HTML5 document and a few divs that separate the app into several individual screens. You will see how these interact in the JavaScript and CSS sections of the tutorial.

index.html

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8"/>
        <title>JavaScript File Encryption App</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link href="http://fonts.googleapis.com/css?family=Raleway:400,700" rel="stylesheet" />
        <link href="assets/css/style.css" rel="stylesheet" />
    </head>

    <body>

        <a class="back"></a>

        <div id="stage">

            <div id="step1">
                <div class="content">
                    <h1>What do you want to do?</h1>
                    <a class="button encrypt green">Encrypt a file</a>
                    <a class="button decrypt magenta">Decrypt a file</a>
                </div>
            </div>

            <div id="step2">

                <div class="content if-encrypt">
                    <h1>Choose which file to encrypt</h1>
                    <h2>An encrypted copy of the file will be generated. No data is sent to our server.</h2>
                    <a class="button browse blue">Browse</a>

                    <input type="file" id="encrypt-input" />
                </div>

                <div class="content if-decrypt">
                    <h1>Choose which file to decrypt</h1>
                    <h2>Only files encrypted by this tool are accepted.</h2>
                    <a class="button browse blue">Browse</a>

                    <input type="file" id="decrypt-input" />
                </div>

            </div>

            <div id="step3">

                <div class="content if-encrypt">
                    <h1>Enter a pass phrase</h1>
                    <h2>This phrase will be used as an encryption key. Write it down or remember it; you won't be able to restore the file without it. </h2>

                    <input type="password" />
                    <a class="button process red">Encrypt!</a>
                </div>

                <div class="content if-decrypt">
                    <h1>Enter the pass phrase</h1>
                    <h2>Enter the pass phrase that was used to encrypt this file. It is not possible to decrypt it without it.</h2>

                    <input type="password" />
                    <a class="button process red">Decrypt!</a>
                </div>

            </div>

            <div id="step4">

                <div class="content">
                    <h1>Your file is ready!</h1>
                    <a class="button download green">Download</a>
                </div>

            </div>
        </div>

    </body>

    <script src="assets/js/aes.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="assets/js/script.js"></script>

</html>

Only one of the step divs is visible at a time. Depending on the choice of the user – to encrypt or decrypt – a class name is set on the body element. With CSS, this class name hides the elements with either the if-encrypt or if-decrypt classes. This simple gating allows us to write cleaner JavaScript that is minimally involved with the UI.

Choose File To Encrypt
Choose File To Encrypt

The JavaScript Code

As I mentioned in the intro, we are going to use the HTML5 FileReader API (support) and the CryptoJS library together. The FileReader object lets us read the contents of local files using JavaScript, but only of files that have been selected explicitly by the user through the file input’s browse dialog. You can see how this is done in the code below. Notice that most of the code handles the transitions between the different screens of the app, and the actual reading of the file happens from line 85.

assets/js/script.js

$(function(){

    var body = $('body'),
        stage = $('#stage'),
        back = $('a.back');

    /* Step 1 */

    $('#step1 .encrypt').click(function(){
        body.attr('class', 'encrypt');

        // Go to step 2
        step(2);
    });

    $('#step1 .decrypt').click(function(){
        body.attr('class', 'decrypt');
        step(2);
    });

    /* Step 2 */

    $('#step2 .button').click(function(){
        // Trigger the file browser dialog
        $(this).parent().find('input').click();
    });

    // Set up events for the file inputs

    var file = null;

    $('#step2').on('change', '#encrypt-input', function(e){

        // Has a file been selected?

        if(e.target.files.length!=1){
            alert('Please select a file to encrypt!');
            return false;
        }

        file = e.target.files[0];

        if(file.size > 1024*1024){
            alert('Please choose files smaller than 1mb, otherwise you may crash your browser. \nThis is a known issue. See the tutorial.');
            return;
        }

        step(3);
    });

    $('#step2').on('change', '#decrypt-input', function(e){

        if(e.target.files.length!=1){
            alert('Please select a file to decrypt!');
            return false;
        }

        file = e.target.files[0];
        step(3);
    });

    /* Step 3 */

    $('a.button.process').click(function(){

        var input = $(this).parent().find('input[type=password]'),
            a = $('#step4 a.download'),
            password = input.val();

        input.val('');

        if(password.length<5){
            alert('Please choose a longer password!');
            return;
        }

        // The HTML5 FileReader object will allow us to read the 
        // contents of the	selected file.

        var reader = new FileReader();

        if(body.hasClass('encrypt')){

            // Encrypt the file!

            reader.onload = function(e){

                // Use the CryptoJS library and the AES cypher to encrypt the 
                // contents of the file, held in e.target.result, with the password

                var encrypted = CryptoJS.AES.encrypt(e.target.result, password);

                // The download attribute will cause the contents of the href
                // attribute to be downloaded when clicked. The download attribute
                // also holds the name of the file that is offered for download.

                a.attr('href', 'data:application/octet-stream,' + encrypted);
                a.attr('download', file.name + '.encrypted');

                step(4);
            };

            // This will encode the contents of the file into a data-uri.
            // It will trigger the onload handler above, with the result

            reader.readAsDataURL(file);
        }
        else {

            // Decrypt it!

            reader.onload = function(e){

                var decrypted = CryptoJS.AES.decrypt(e.target.result, password)
                                        .toString(CryptoJS.enc.Latin1);

                if(!/^data:/.test(decrypted)){
                    alert("Invalid pass phrase or file! Please try again.");
                    return false;
                }

                a.attr('href', decrypted);
                a.attr('download', file.name.replace('.encrypted',''));

                step(4);
            };

            reader.readAsText(file);
        }
    });

    /* The back button */

    back.click(function(){

        // Reinitialize the hidden file inputs,
        // so that they don't hold the selection 
        // from last time

        $('#step2 input[type=file]').replaceWith(function(){
            return $(this).clone();
        });

        step(1);
    });

    // Helper function that moves the viewport to the correct step div

    function step(i){

        if(i == 1){
            back.fadeOut();
        }
        else{
            back.fadeIn();
        }

        // Move the #stage div. Changing the top property will trigger
        // a css transition on the element. i-1 because we want the
        // steps to start from 1:

        stage.css('top',(-(i-1)*100)+'%');
    }

});

I obtain the contents of the files as a data uri string (support). Browsers allow you to use these URIs everywhere a regular URL would go. The benefit is that they let you store the content of the resource directly in the URI, so we can, for example, place the contents of the file as the href of a link, and add the download attribute (read more) to it, to force it to download as a file when clicked.
I use the AES algorithm to encrypt the data uri with the chosen password, and to offer it as a download. The reverse happens when decrypting it. No data ever reaches the server. You don’t even need a server for that matter, you can open the HTML directly from a folder on your computer, and use it as is.

Enter a Pass Phrase
Enter a Pass Phrase

The CSS

I will present only the more interesting parts of the CSS here, you can see the rest in the stylesheet from the downloadable zip. The first thing to present, are the styles that create the layout and its ability to scroll smoothly between screens by changing the top property of the #stage element.

assets/css/styles.css

body{
    font:15px/1.3 'Raleway', sans-serif;
    color: #fff;
    width:100%;
    height:100%;
    position:absolute;
    overflow:hidden;
}

#stage{
    width:100%;
    height:100%;
    position:absolute;
    top:0;
    left:0;

    transition:top 0.4s;
}

#stage > div{  /* The step divs */
    height:100%;
    position:relative;
}

#stage h1{
    font-weight:normal;
    font-size:48px;
    text-align:center;
    color:#fff;
    margin-bottom:60px;
}

#stage h2{
    font-weight: normal;
    font-size: 14px;
    font-family: Arial, Helvetica, sans-serif;
    margin: -40px 0 45px;
    font-style: italic;
}

.content{
    position:absolute;
    text-align:center;
    left:0;
    top:50%;
    width:100%;
}
Because the step divs are set to a 100% width and height, they automatically take the full dimensions of the browser window without having to be resized.
Another interesting piece of code, are the conditional classes that greatly simplify our JavaScript:
[class*="if-"]{
    display:none;
}

body.encrypt .if-encrypt{
    display:block;
}

body.decrypt .if-decrypt{
    display:block;
}

This way, the encrypt and decrypt classes of the body control the visibility of the elements that have the respective if-* class.

We’re done!

With this our JavaScript encryption app is ready! You can use it to share pictures and documents with friends by sending them the version encrypted with a pre-agreed pass phrase. Or you can put the HTML of the app on a flash drive, along with your encrypted files, and open the index.html directly to decrypt them.

Selasa, 20 November 2012

PHP Source Code - Sistem Informasi Kepegawaian

Sistem Informasi Kepegawaian berbasis platform PHP dengan database My SQL

Pada aplikasi ini karyawan dapat mengajukan permohonan cuti dan mendapatkan persetujuan cuti dari atasan secara online. Atasan dapat melihat daftar riwayat cuti karyawan.

Download source code

Program pendukung
1. PHP Triad
2. My SQL
3. PHP Editor

Sabtu, 10 November 2012

Tips Belajar Jquery Mengenal Selector JQuery Basic Filter (:odd)


Mengenal Selector JQuery Basic Filter (:odd)
match odd elements
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="../jquery-latest.js"></script>

  <script>
  $(document).ready(function(){
    $("tr:odd").css("background-color", "#bbbbff");
  });
  </script>
  <style>
  table {
    background:#f3f7f5;
  }
  </style>
</head>
<body>
  <table border="1">
    <tr><td>Row with Index #0</td></tr>
    <tr><td>Row with Index #1</td></tr>
    <tr><td>Row with Index #2</td></tr>
    <tr><td>Row with Index #3</td></tr>
  </table>
</body>
</html>
Perintah
$(“tr:odd”).css(“background-color”, “#bbbbff”);
tadinya saya bingung juga dengan kata-kata odd setelah lihat cara kerjanya ternyata odd itu disini diartikan ganjil.
digunakan untuk menset css “background-color”, “#bbbbff” pada tr yang ganjil dalam suatu table didocument html.

Aplikasi Basis Web Menghitung Luas Pesegipanjang


Untuk tutorial pertama ini, kita akan membahas memabuat aplikasi sederhana menghitung luas persegi panjang dengan javascript.
Sebelum melangkah lebih jauh, tentu ada yang bertanya kenapa sih kita perlu mempelajari javascript ?
Jika anda ingin menjadi seorang web developer professional, anda harus menguasai javascript.
Memanganya apa yang dapat kita buat dengan javascript ?
  • kita dapat membuat menu yang cantik di web
  • kita bisa membuat gambar dengan javascript
  • kita bisa membuat chart atau grafik
  • Dengan lahirnya HTML 5 kita dapat membuat aplikasi yang dapat menyimpan data pada database.
  • Kita bisa juga loh buat game dengan javascript
  • Kita bisa membuat Sistem Informasi Geografi, dengan memanfaatkan Googlemap.
  • Kita bisa membuat Aplikasi Mobile juga loh
  • Kalau anda suka berkunjung ke detik.com atau kompas.com tentu mengalami munculnya iklan yang langsung muncul dan anda harus mengclosenya. Nah kita juga bisa buat itu dengan javascript
Manfaat diatas  adalah manfaat dari sisi teknis, kita sering melupakan manfaat dari sisi non teknis. Hayoo coba tanyakan dalam diri kita masing-masing manfaat non teknis apa yang bisa kita dapat.
ini jawaban versi saya
  • Menambah rasa kepercayaan diri
  • Membahagiakan orang tua
  • Dapat membantu orang lain
  • Dapat menghasilkan uang
  • Dapat memperbanyak teman
  • Dapat menjadi terkenal
  • Dan masih ada beberapa yang belum saya sebutkan
Wah kalau gini aku semangat deh belajarnya 
Untuk itu tambah semangat lagi khusus untuk topik javascript boleh mengusulkan materi-materi apa saja yang diusulkan untuk dijadikan tutorial. Insya Allah saya akan usahakan untuk menulis tutorialnya.
Ayo semangaaaatttt. dari pada waktu dihabiskan untuk hal-hal yang sia-sia, lebih baik kita gunakan untuk hal yang bermanfaat untuk kehidupan kita.
Jika kita membayangkan tahun depan jadi seorang web developer handal. apakah itu dapat terwujud dengan santai-santai dan banyak buang waktu ?
Yang tidak kalah penting, kita juga perlu memahami DOM (Document Obect Model). Dengan memahami DOM akan memudahkan kita mengatur object-object pada dokumen HTML.
Dalam Pikiran kita, apa bila kita ingin membuat Aplikasi menghitung luas persegi panjang tentunya kita harus menyediakan kotak teks untuk menginputkan nilai panjang dan lebar dan kotak teks untuk menampilkan luasnya.
Sekarang mari kita mulai pembuatan aplikasinya. Untuk Editornya anda bisa menggunakan Teks Editor apa saja. Pada tutorial ini saya menggunakan Editor yang memang khsusus untuk mendevelop aplikasi web.
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<title>Menghitung Luas Persegi Panjang</title>
		<style>
			div {border: 1px solid #999; padding:10px; width:300px; background:#e3e3e3}
			label {width:100px; float:left; }
			input {border:1px solid #999; border-radius:6px; margin-bottom:10px;)
		</style>
		<script type="text/javascript">
			function hitungLuas(){
				panjang = document.getElementById("txtPanjang").value;
				lebar = document.getElementById("txtLebar").value;
				if (panjang == ""){
					alert("Panjang Harus diisi !");
					return;
				}else if (lebar == ""){
					alert("Lebar Harus diisi !");
					return;
				}
				if (isNaN(panjang)){
					alert("Panjang Harus diisi dengan angka !");
					return;
				}if (isNaN(lebar)){
					alert("Lebar Harus diisi dengan angka !");
					return;
				}
				Luas = panjang * lebar;
				document.getElementById("txtLuas").value =  Luas;

			}
			function resetForm(){
				document.getElementById("txtPanjang").value="";
				document.getElementById("txtLebar").value="";
				document.getElementById("txtLuas").value="";
			}

		</script>
	</head>
	<body>
		<div>
		<h3>Menghhitung Luas Persegi Panjang</h3>
		<label for="panjang">Panjang </label>: <input type="text" id="txtPanjang" name="txtPanjang"/><br/>
		<label>Lebar </label>: <input type="text" id="txtLebar" name="txtLebar"/><br/>
		<input type="button" id="btnHitung" value="Hitung Luas" onclick="hitungLuas();">&nbsp;<input type="button" id="btnReset" value="Reset" onclick="resetForm();"><br/>
		<label>Luas </label>: <input type="text" readonly="true" id="txtLuas" name="txtLuas"/>
		</div>
	</body>
</html>
Simpan kode di atas dengan nama persegipanjang.html
Perhatikan kode diatas untuk mempercantik tampilan pada bagian kode htmlnya kita menambahkan tag<div> dan <label>

Kita juga mulai bermain dengan css untuk mengatur dan memperindah tampilan
<style>
	div {border: 1px solid #999; padding:10px; width:300px; background:#e3e3e3}
	label {width:100px; float:left; }
	input {border:1px solid #999; border-radius:6px; margin-bottom:10px;)
</style>

Pada bagian javascriptnya kita juga sudah menambahkan validasi inputan panjang dan lebar

if (panjang == ""){
	alert("Panjang Harus diisi !");
	return;
}else if (lebar == ""){
	alert("Lebar Harus diisi !");
	return;
}
if (isNaN(panjang)){
	alert("Panjang Harus diisi dengan angka !");
	return;
}if (isNaN(lebar)){
	alert("Lebar Harus diisi dengan angka !");
	return; 
} 
Nilai pada inputan panjang dan lebar akan dicek apakah sudah diisi atau belum jika belum diisi maka  akan muncul pesan peringatan agar user mengisi nilainya.
Selain itu untuk memastikan bahwa user menginputkan nilai yang benar, maka apabilea user menginputkan selain angka maka akan muncul juga pesan peringatan bahwa panjang atau lebar harus diisi dengan angka untuk pengecekannya kita manfaatkan fungsi isNaN
Kita juga menambahakan tombol untuk mereset nilai panjang lebar dan luas. Gunanya jika kita ingin menghitung lagi kita tidak perlu mengosongkan secara manual.
Sekarang mari kita coba jalankan dibrowser apakah kode yang baru ini  telah menutupi kekurangan-kekurangan pada kode yang lama
Lihat tampilan sudah lebih enak dilihat.
Klik tombol Hitung Luas, karena nilai panjang belum diisi maka akan muncul peringatan.
Isi nilai panjang atau lebar dengan nilai yang selain angka. Lalu klik tombol Hitung Luas, karena nilai lebar diisi dengan selain angka maka akan muncul peringatan “Lebar Harus diisi dengan angka”
Isi nilai panjang atau lebar dengan angka, Lalu klik tombol Hitung Luas, Tidak ada lagi peringatan dan Nilai Luas sudah terisi.
Bagaimana makin tertarikkan dengan javascript :)

Selasa, 05 Juli 2011

Membuat Animasi Image Rotator Dengan JQuery

Artikel kali ini akan membahas tentang animasi image yang sering di gunakan pada setiap sisi halaman website, yaitu image rotator. Image rotator adalah cara menampilkan daftar image yang diganti satu per satu dalam suatu periode. Animasi ini biasanya di pasang pada space banner di dalam halaman website, agar pengunjung dapat melihat satu per satu secara bergantian produk yang di tawarkan pada banner tersebut.
Untuk membuat efek image rotator dengan JavaScript biasa tentu akan sulit, namun dengan bantuan jQuery anda tidak perlu menulis banyak kode, karena efek animasi seperti fadeIn (menampilkan perlahan-lahan) dan fadeOut (menyembunyikan perlahan-lahan) sudah disediakan oleh library jQuery standar.

Berikut adalah source code untuk melakukan image rotator dengan jQuery (masukan kode di bawah diantara tag HEAD).
 
<script type="text/javascript" src="../jquery.js"></script>
  <script type="text/javascript">
    // tentukan lokasi atau directory gambar-gambar yang akan di load
    var imageDirectory = './'; 
    /* tentukan gambar-gambar yang ingin di load dalam lokasi yang sudah di tentukan sebelumnya
    tidak ada batasan berapa banyak anda memasukan gambar */
    var imageList = ['slide1.jpg','slide2.jpg','slide3.jpg','slide4.jpg'];
 
    // flag yang digunakan untuk mendeteksi berapa banyak gambar yang sudah di load
    var imageHasLoad = 0;
 
    // flag yang digunakan untuk melakukan rotator berdasar urutan gambar
    var imagePosition = 0;
 
    /* pre-load image, agar gambar-gambar yang ingin ditampilkan sudah di load 
       sebelum halaman web di load secara keseluruhan */ 
    $(imageList).each( // looping isi array gambar
        function(){
            var Img = new Image(); // buat object gambar di javascript
            Img.src = imageDirectory+this // lokasi gambar di tentukan dari masing-masing nilai array yang sudah ditentukan sebelumnya
            $(Img).load( // membuat fungsi ketika gambar selesai di load
              function(){
                  imageHasLoad++; // setup flag berapa banyak gambar yang sudah di load
                  if(imageHasLoad == imageList.length) // jika semua gambar selesai di load
                      insertImages(); 
              }
            );      
        }
    ); 
    // fungsi untuk memasukan HTML TAG gambar di dalam sebuah elemen DIV 
    function insertImages(){
        var imgStr = '';
        $(imageList).each( // looping isi array gambar
           function(){
           // gambar secara default di sembunyikan terlebih dahulu 
              imgStr += '<img src="'+imageDirectory+this+'" border="0" style="display:none" />'; 
           }
        );
        $('#divSlideShow').html(imgStr); // masukkan semua HTML TAG gambar ke dalam element dengan ID #divSlideShow
        rotateImages(); // lakukan animasi rotator
    }  
    // fungsi untuk melakukan rotator 
    function rotateImages(){
        /* logika pada fungsi ini adalah sembuyikan image yang sudah tampil sebelumnya, lalu setelah selesai di sembunyikan
     maka tampilkan image selanjutnya. Menyembunyikan dan menampilkan image dengan fungsi fadeOut dan fadeIn dari jQuery */
     $($('#divSlideShow').find('img')[imagePosition > 0 ? imagePosition - 1 : imageList.length - 1]).fadeOut(
         'slow',
   function(){ // fungsi yang akan dijalankan setelah gambar sebelumnya selesai disembuyikan
    $($('#divSlideShow').find('img')[imagePosition]).fadeIn();
   }
     );
     // jika posisi rotator sudah sama dengan jumlah image yang di load sebelumnya, maka kembalikan ke posisi awal atau nol
  if(imagePosition == imageList.length - 1) 
   imagePosition = 0; 
     else 
   imagePosition++; 
     setTimeout('rotateImages()',2000); // lama rotasi per image adalah 2000 miliseconds atau 2 detik
    }
  </script>

Coba perhatikan pada source code diatas ada metoda untuk memanggil gambar secara pre-loading, tujuannya adalah agar gambar-gambar yang akan di load secara diam-diam di load satu per satu sebelum seluruh halaman web selesai di load, jadi pengunjung tidak perlu menunggu lama-lama untuk melihat image rotator anda.
Selama pengunjung menunggu tampilkan saja text “loading image…” atau gambar GIF yang menarik. Masukan kode di bawah diantara tag BODY.

<!-- tampilkan text "loading images" selama pengunjung menunggu hasil pre-load image -->
<div id="divSlideShow">loading images...</div>

Contoh :





Animasi ini dapat anda tempatkan di setiap sisi halaman website sesuai keinginan anda.
Semoga bisa bermanfaat… ^_^