/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package caesarcipher;
/**
*
* @author PDK
*/
public class CaesarCrypt {
private final String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+-gfuifyuvfyifrghvhyifyutcyi";
public String encrypt(String plainText,int shiftKey)
{
// plainText = plainText.toLowerCase();
String cipherText="";
int charPosition;
int keyVal;
char replaceVal;
for(int i=0; i < plainText.length(); i++)
{
charPosition = chars.indexOf(plainText.charAt(i));
keyVal = (charPosition + shiftKey) % chars.length();
replaceVal = this.chars.charAt(keyVal);
cipherText += replaceVal;
}
return cipherText;
}
public String decrypt(String cipherText, int shiftKey)
{
// cipherText = cipherText.toLowerCase();
String plainText="";
int charPosition;
int keyVal;
char replaceVal;
for(int i=0;i<cipherText.length();i++)
{
charPosition = this.chars.indexOf(cipherText.charAt(i));
keyVal = charPosition - shiftKey;
if(keyVal < 0)
{
keyVal = this.chars.length() + keyVal;
}
replaceVal = this.chars.charAt(keyVal);
plainText += replaceVal;
}
return plainText;
}
}
MainScreen.java
private void btnDecActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String cipherText = txtEnc.getText();
int shiftKey= Integer.parseInt(txtShift.getText());
CaesarCrypt cc = new CaesarCrypt();
String plainText = cc.decrypt(cipherText, shiftKey);
lblDec.setText(plainText);
}
private void btnEncActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String plainText = txtDec.getText();
int shiftKey= Integer.parseInt(txtShift.getText());
CaesarCrypt cc = new CaesarCrypt();
String cipherText = cc.encrypt(plainText, shiftKey);
lblEnc.setText(cipherText);
txtEnc.setText(cipherText);
}