分类目录归档:Information Security

infomation and communication systems security

XML Encryption and Decryption for Element

Huan Meng

XML Encryption and Decryption for Element

1. Encryption function

public static org.w3c.dom.Element EncryptElement(
final String strTagNameOfElementToEncrypt,
final org.w3c.dom.Element elemParent) throws Exception {
org.apache.xml.security.Init.init();

String strEncryptionAlgorithm = org.apache.xml.security.encryption.XMLCipher.AES_128;

String strEncryptionAlgorithmProvider = null;

String strEncryptionDigestAlgorithm = org.apache.xml.security.utils.Constants.ALGO_ID_DIGEST_SHA1;

String strEncryptionKeyGeneratorAlgorithm = “AES”;

String strEncryptionKeyGeneratorAlgorithmProvider = null;

int nEncryptionKeyGeneratorSize = 128;

String strEncryptionKeyWrapAlgorithm = org.apache.xml.security.encryption.XMLCipher.RSA_OAEP;

String strEncryptionKeyWrapAlgorithmProvider = null;

final org.w3c.dom.Element domParent =elemParent;
final org.w3c.dom.Document domDocument = domParent.getOwnerDocument();
final org.w3c.dom.NodeList nlToEncrypts = domParent
.getElementsByTagName(strTagNameOfElementToEncrypt);
if (null == nlToEncrypts) {
final String strErrorMessage = “org.w3c.dom.Element.getElementsByTagNameNS unexpectedly returned null”;
// XMLSecurityApacheExtension.log.error(strErrorMessage);
return null;
}

if (1 != nlToEncrypts.getLength()) {
final String strErrorMessage = “org.w3c.dom.Element.getElementsByTagNameNS unexpectedly returned “
+ nlToEncrypts.getLength() + ” nodes”;
// XMLSecurityApacheExtension.log.error(strErrorMessage);
return null;
}
final org.w3c.dom.Element domToEncrypt = (org.w3c.dom.Element) nlToEncrypts
.item(0);
final org.w3c.dom.Element domTempParent = domDocument
.createElement(“Parent”);
final org.w3c.dom.Element domTempToEncrypt = (org.w3c.dom.Element) domTempParent
.appendChild(domToEncrypt.cloneNode(true));

String pass=”123456″;
FileInputStream in=new FileInputStream(“C:\\Users\\mina\\tomcat.keystore”);
KeyStore ks=KeyStore.getInstance(“JKS”);
ks.load(in,pass.toCharArray());
java.security.cert.Certificate cert=ks.getCertificate(“tomcat”);

final X509Certificate certificate = (X509Certificate)cert;
// final String certificate = “MIIEsjCCApoCAQAwDQYJKoZIhvcNAQEEBQAwga8xCzAJBgNV

BAYTAkNIMQ8wDQYDVQQIEwZadXJpY2gxDzANBgNVBAcTBlp1

cmljaDEhMB8GA1UEChMYQWJoaUNlcnRpZmljYXRlQXV0aG9ya

XR5MRUwEwYDVQQLEwxGaXJzdFR5cGUgQ0ExITAfBgNVBAMT

GEFiaGlDZXJ0aWZpY2F0ZUF1dGhvcml0eTEhMB8GCSqGSIb3DQ

EJARYSYWJzQHp1cmljaC5pYm0uY29tMB4XDTA3MDUwNzEzMD

AwNloXDTA3MDgxNTEzMDAwNlowgY0xCzAJBgNVBAYTAkNIMQ

8wDQYDVQQIEwZadXJpY2gxDzANBgNVBAcTBlp1cmljaDEQMA4G

A1UEChMHSUJNIFpSTDESMBAGA1UECxMJYWJoaSB0ZXN0MRM

wEQYDVQQDEwphYmhpbGFwdG9wMSEwHwYJKoZIhvcNAQkBFhJ

hYmhpQGNzYWlsLm1pdC5lZHUwggEiMA0GCSqGSIb3DQEBAQUAA

4IBDwAwggEKAoIBAQCskkmbBSXMRT9FuoE+hn0XvSKCJhedXG6kt

gnjqODbDXlWHqDW+Jxj/N7CD1Nxry0lIsKNVcgJ8QXpX21aTDH3lMg

dAZVyQYkVA24fGolV6fRFSybwaZ5/IxTW3H29wiZJhSKii5jSFfA/XPDTE

FucT6u4VWR81dXCtd528T4vMXbF+QuWhfn5u5MZBncsWZr9YC5cKeV

5Z6/qx9LpnfjHKeTNAlscv93YDYavkKt6kJX6hV/zZ3bIiJ90RxUE8UiVbY

5PORRfY7uHU+Ga0MTbOj0Y0VGr++DQfrYDm1Prm0IRWFm4pjkNRZT

mEZRxDtJ+IbNFfQC/SrcCSwO+e+odAgMBAAEwDQYJKoZIhvcNAQEEB

QADggIBAMVyOhAHcw4iZnsjneSFWLSveEutSicl6nzjL7rRm9vQjZYna4V

CYlUnnoCQoqms82KKxYohlvU1zFS90x7xKE5Of20NPIfzFSuUsxBQOtsDt

o+DCPoAAk3HmXcUQS/l2ZGJPeL4W6FEJrx4ewwMdN5LnrtqbaBMGJP

onDWYqQHv+kPyc0a8djq3C3vFN1MfYIVSMDser7NLqgdqKjNKP00Keui

WoN72c5bgsRl+/S+QuVaZAgLkOVzN4r3RX+jIZe2TJgYzOlCuUC8/PFnF

LGcukpIv2aUzGXx8mc7yhboInwbBlleN6xJnDWLwRivA9Tf6WrymH1L6K

jPBBIFq9S17dXQyFRGy0BNVHaLEu3jBk8nv0cnrjI2bCBiH9rxnmqrq5VU

y0gCHxlnNNKDx7cyf98/BlbtKh43t9gb3goaKUSYWO8mkA6eT6AAIpjCW

FP+K8Y3R4T9jhXBfCROTa/fpzKtN9uIMMgV6oKTwnB+ATEhGhkzkSfny

mz5H0orYA2gkU8OimcZCQTAtSLkXyiyE8u3O61vR5SEyb2diVIdCkqwK8

dQT4NMX2LZwsXULUV7z8fclKlvImC++r1DwBDsVtbwwlE9DxviL9sBtS2

MG+oZmYA0YwrIOqOvnjI7avxFV7MzzOWRC+06WNJAnHVlFCdiR1b9

Q7kteqDZ0RxzC”;

//org.eclipse.higgins.sts.utilities.CertificateHelper
//.fromString(strCertificate);

javax.crypto.KeyGenerator keyGenerator = null;
if (null == strEncryptionKeyGeneratorAlgorithmProvider)
keyGenerator = javax.crypto.KeyGenerator.getInstance(“AES”);
//.getInstance(“strEncryptionKeyGeneratorAlgorithm”);
else
keyGenerator = javax.crypto.KeyGenerator.getInstance(
“strEncryptionKeyGeneratorAlgorithm”,
strEncryptionKeyGeneratorAlgorithmProvider);
keyGenerator.init(nEncryptionKeyGeneratorSize);
final javax.crypto.SecretKey secretKey = keyGenerator.generateKey();
final java.security.PublicKey publicKeyRP = certificate.getPublicKey();
org.apache.xml.security.encryption.XMLCipher keyCipher = null;
if (null == strEncryptionKeyWrapAlgorithmProvider)
keyCipher = org.apache.xml.security.encryption.XMLCipher
.getInstance(strEncryptionKeyWrapAlgorithm);
else
keyCipher = org.apache.xml.security.encryption.XMLCipher
.getProviderInstance(strEncryptionKeyWrapAlgorithm,
strEncryptionKeyWrapAlgorithmProvider);
keyCipher.init(org.apache.xml.security.encryption.XMLCipher.WRAP_MODE,
publicKeyRP);
final org.apache.xml.security.keys.KeyInfo keyInfoKey = new org.apache.xml.security.keys.KeyInfo(
domDocument);
final java.security.MessageDigest mdSha1 = java.security.MessageDigest
.getInstance(“SHA-1”);
final byte[] byteThumbPrint = mdSha1.digest(certificate.getEncoded());
final org.w3c.dom.Document domParentDocument = domParent
.getOwnerDocument();
final org.w3c.dom.Element domSTR = domParentDocument
.createElementNS(
http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd“,
“SecurityTokenReference”);
final org.w3c.dom.Element domKeyIdentifier = domParentDocument
.createElementNS(
http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd“,
“KeyIdentifier”);
domKeyIdentifier
.setAttribute(
“ValueType”,
http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1“);
domKeyIdentifier
.setAttribute(
“EncodingType”,
http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary“);
String strThumbprint = org.apache.xml.security.utils.Base64
.encode(byteThumbPrint);
// org.eclipse.higgins.sts.utilities.XMLHelper.setTextContent(
// domKeyIdentifier, strThumbprint);
domKeyIdentifier.setTextContent(strThumbprint);
domSTR.appendChild(domKeyIdentifier);
keyInfoKey.addUnknownElement(domSTR);
final org.apache.xml.security.encryption.EncryptedKey encryptedKey = keyCipher
.encryptKey(domDocument, secretKey);
encryptedKey.setKeyInfo(keyInfoKey);
final org.apache.xml.security.encryption.EncryptionMethod encryptionMethod = encryptedKey
.getEncryptionMethod();
final org.w3c.dom.Element elemDigestMethod = domDocument
.createElementNS(
org.apache.xml.security.utils.Constants.SignatureSpecNS,
“DigestMethod”);
elemDigestMethod
.setAttribute(“Algorithm”, strEncryptionDigestAlgorithm);
encryptionMethod.addEncryptionMethodInformation(elemDigestMethod);
org.apache.xml.security.encryption.XMLCipher xmlCipher = null;
if (null == strEncryptionAlgorithmProvider)
xmlCipher = org.apache.xml.security.encryption.XMLCipher
.getInstance(strEncryptionAlgorithm);
else
xmlCipher = org.apache.xml.security.encryption.XMLCipher
.getProviderInstance(strEncryptionAlgorithm,
strEncryptionAlgorithmProvider);
xmlCipher.init(
org.apache.xml.security.encryption.XMLCipher.ENCRYPT_MODE,
secretKey);
final org.apache.xml.security.encryption.EncryptedData encryptedData = xmlCipher
.getEncryptedData();
final org.apache.xml.security.keys.KeyInfo keyInfoEncryption = new org.apache.xml.security.keys.KeyInfo(
domDocument);
keyInfoEncryption.add(encryptedKey);
encryptedData.setKeyInfo(keyInfoEncryption);
System.out.println(“do final, encrypt the Element”);
//xmlCipher.doFinal(domDocument, domTempToEncrypt, false);
xmlCipher.doFinal(domDocument, domTempToEncrypt,false);
final org.w3c.dom.NodeList nlEncryptedData = domTempParent
.getElementsByTagNameNS(
org.apache.xml.security.utils.EncryptionConstants.EncryptionSpecNS,
“EncryptedData”);
if (1 != nlEncryptedData.getLength()) {
throw new Exception(“One EncryptedData Not Found!”);
}
org.w3c.dom.Element domEncryptedData = (org.w3c.dom.Element) nlEncryptedData
.item(0);
System.out.println(“********************”+domEncryptedData.getNodeType());
// org.eclipse.higgins.sts.utilities.XMLHelper
// .stripNewLinesFromElement((org.w3c.dom.Element) nlEncryptedData
// .item(0));
domParent.replaceChild(domEncryptedData, domToEncrypt);

System.out.println(“encrypt:”+domEncryptedData);
// org.w3c.dom.Element elemResult = null;
// elemResult.set(domParent);
return domParent;
//return domEncryptedData;
}
//**************

2. Decryption function

public static org.w3c.dom.Element DecryptElement
(final org.w3c.dom.Element elemEncryptedData,
final PrivateKey privateKey) throws Exception
{
String strEncryptionAlgorithm = org.apache.xml.security.encryption.XMLCipher.AES_128;

String strEncryptionAlgorithmProvider = null;

String strEncryptionKeyGeneratorAlgorithm = “AES”;

// int nEncryptionKeyGeneratorSize = 128;

String strEncryptionKeyWrapAlgorithm = org.apache.xml.security.encryption.XMLCipher.RSA_OAEP;

String strEncryptionKeyWrapAlgorithmProvider = null;

//XMLSecurityApacheExtension.log.trace(“DecryptElement”);

final org.w3c.dom.Element domEncryptedData = elemEncryptedData;
final org.w3c.dom.NodeList nlEncryptedKey = domEncryptedData.getElementsByTagNameNS
(org.apache.xml.security.utils.EncryptionConstants.EncryptionSpecNS,
org.apache.xml.security.utils.EncryptionConstants._TAG_ENCRYPTEDKEY);
if (null == nlEncryptedKey)
{
//XMLSecurityApacheExtension.log.trace(“No EncryptedKey found (getElementsByTagName returned null)”);
}
else if (0 == nlEncryptedKey.getLength())
{
//XMLSecurityApacheExtension.log.trace(“No EncryptedKey found (0 == getLength())”);
}
else
{
final org.w3c.dom.Document domDocument = domEncryptedData.getOwnerDocument();
final org.w3c.dom.Element elemEncryptedKey = (org.w3c.dom.Element)nlEncryptedKey.item(0);
final org.w3c.dom.NodeList nlKeyEncryptionMethod = elemEncryptedKey.getElementsByTagNameNS
(org.apache.xml.security.utils.EncryptionConstants.EncryptionSpecNS,
org.apache.xml.security.utils.EncryptionConstants._TAG_ENCRYPTIONMETHOD);
String strKeyEncryptionMethod = null;
if (null == nlKeyEncryptionMethod)
{
//XMLSecurityApacheExtension.log.trace(“No EncryptionMethod found”);
strKeyEncryptionMethod = strEncryptionKeyWrapAlgorithm;
}
else if (0 == nlKeyEncryptionMethod.getLength())
{
//XMLSecurityApacheExtension.log.trace(“No EncryptionMethod found”);
strKeyEncryptionMethod = strEncryptionKeyWrapAlgorithm;
}
else
{
final org.w3c.dom.Element elemKeyEncryptionMethod = (org.w3c.dom.Element)nlKeyEncryptionMethod.item(0);
strKeyEncryptionMethod = elemKeyEncryptionMethod.getAttribute(org.apache.xml.security.utils.EncryptionConstants._ATT_ALGORITHM);
}
org.apache.xml.security.encryption.XMLCipher keyCipher = null;
if (null == strEncryptionKeyWrapAlgorithmProvider)
keyCipher = org.apache.xml.security.encryption.XMLCipher.getInstance
(strKeyEncryptionMethod);
else
keyCipher = org.apache.xml.security.encryption.XMLCipher.getProviderInstance
(strKeyEncryptionMethod,
strEncryptionKeyWrapAlgorithmProvider);
keyCipher.init
(org.apache.xml.security.encryption.XMLCipher.UNWRAP_MODE,
privateKey);
final org.apache.xml.security.encryption.EncryptedKey encryptedKey = keyCipher.loadEncryptedKey
(domDocument,
elemEncryptedKey);
final java.security.Key keySecret = keyCipher.decryptKey
(encryptedKey,
strEncryptionKeyWrapAlgorithm);//用私钥去解密出对称密钥

final javax.crypto.SecretKey secretKey = (javax.crypto.SecretKey)keySecret;//对称密钥
final byte [] encodedSecretKey = secretKey.getEncoded();
final javax.crypto.spec.SecretKeySpec secretKeySpec = new javax.crypto.spec.SecretKeySpec
(encodedSecretKey, strEncryptionKeyGeneratorAlgorithm);//AES类型的密钥
org.apache.xml.security.encryption.XMLCipher xmlCipher = null;
if (null == strEncryptionAlgorithmProvider)
xmlCipher = org.apache.xml.security.encryption.XMLCipher.getInstance
(strEncryptionAlgorithm);
else
xmlCipher = org.apache.xml.security.encryption.XMLCipher.getProviderInstance
(strEncryptionAlgorithm,
strEncryptionAlgorithmProvider);
xmlCipher.init
(org.apache.xml.security.encryption.XMLCipher.DECRYPT_MODE,
secretKeySpec);
final org.w3c.dom.Document domResultDocument = xmlCipher.doFinal
(domDocument,
domEncryptedData,
false);
// final org.eclipse.higgins.sts.api.IElement elemResult = new org.eclipse.higgins.sts.common.Element();
// elemResult.set
// (domResultDocument.getDocumentElement());
return domResultDocument.getDocumentElement();
}
return null;
}

Message Confidentiality Practice(RSA and base 64)

Click here to download code (NB: You should register first)

[download id=”3″]

 

Part 1

Message Confidentiality
Practice

This demo made a simple implementation of Message Confidentiality. It encrypt/decrypt with a message using public/private key pair.

Author: Huan Meng huanm@kth.se

 

The process of operation:

1. Generate two random numbers:

 

2. Generate key pairs:

 

3. Click “Ecryption” and get the Ciphertext(record the ciphertext). Input the record ciphertext or delete the plaintext and click “Decryption”:

 

The main source code is as follows:

unit Unit1;

 

interface

 

uses

Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,

StdCtrls, Spin, ComCtrls;

 

type

TForm1 = class(TForm)

Button1: TButton;

Button2: TButton;

Edit1: TEdit;

Edit2: TEdit;

Edit3: TEdit;

Edit4: TEdit;

Edit5: TEdit;

Edit6: TEdit;

Edit7: TEdit;

Edit8: TEdit;

Edit9: TEdit;

Edit10: TEdit;

Label1: TLabel;

Label2: TLabel;

Label3: TLabel;

Label4: TLabel;

Label5: TLabel;

Label6: TLabel;

Label7: TLabel;

Label8: TLabel;

Label9: TLabel;

Label10: TLabel;

Button3: TButton;

Button4: TButton;

Button5: TButton;

edit13: TMemo;

edit11: TRichEdit;

Label11: TLabel;

Label12: TLabel;

Edit12: TEdit;

Label14: TLabel;

procedure Button1Click(Sender: TObject);

procedure Button2Click(Sender: TObject);

procedure Button3Click(Sender: TObject);

procedure Button4Click(Sender: TObject);

procedure Button5Click(Sender: TObject);

procedure Button6Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

 

var

Form1: TForm1;

 

implementation

 

uses ranlib, FGInt, FGIntPrimeGeneration, FGIntRSA;

 

{$R *.DFM}

 

procedure TForm1.Button1Click(Sender: TObject);

 

var seed, i: integer;

var s,s2: string;

 

begin

seed := Round(Time()*3600000.0);

 

WRandomInit(seed);

 

for i := 1 to 20 do begin

WRandom();

WIRandom(0,1000);

end;

s:=floattostr(WIRandom(0,1000000000));

s2:=floattostr(WIRandom(0,1000000000));

 

edit1.text:=s;

edit2.text:=s2;

end;

 

procedure TForm1.Button2Click(Sender: TObject);

var

n, e, d, dp, dq, p, q, phi, one, two, gcd, temp, nilgint,te1,te2,te3 : TFGInt;

test, signature : String;

p1,q1,dp1,dq1,e1,d1,n1,nil1,gcdStr:string;

ok : boolean;

begin

Base10StringToFGInt(edit1.text, p);

PrimeSearch(p);

Base256StringToFGInt(edit2.text, q);

PrimeSearch(q);

// Compute the modulus

FGIntMul(p, q, n);

 

// Compute p-1, q-1 by adjusting the last digit of the GInt

p.Number[1] := p.Number[1] – 1; 1

q.Number[1] := q.Number[1] – 1;

// Compute phi(n)

FGIntMul(p, q, phi);//作(p-1)*(q-1)=phi

// Choose a public exponent e such that GCD(e,phi)=1

Base10StringToFGInt(‘65537’, e);

Base10StringToFGInt(‘1’, one);

Base10StringToFGInt(‘2’, two);

FGIntGCD(phi, e, gcd);

While FGIntCompareAbs(gcd, one) <> Eq Do

Begin

FGIntadd(e, two, temp);

FGIntCopy(temp, e);

FGIntGCD(phi, e, gcd);

End;

FGIntToBase10String(e,gcdstr);

edit12.text:=gcdstr;

FGIntDestroy(two);

FGIntDestroy(one);

FGIntDestroy(gcd);

 

FGIntModInv(e, phi, d);

FGIntModInv(e, p, dp);

FGIntModInv(e, q, dq);

p.Number[1] := p.Number[1] + 1;

q.Number[1] := q.Number[1] + 1;

Base10StringToFGInt(‘100′, te1);

Base10StringToFGInt(’25’, te2);

FGIntMul(te1,te2,te3);

FGIntToBase10String(p,p1);

edit3.text:=p1;

FGIntToBase10String(q,q1);

edit4.text:=q1;

FGIntToBase10String(dp,dp1);

edit5.text:=dp1;

FGIntToBase10String(dq,dq1);

edit6.text:=dq1;

FGIntToBase10String(e,e1);

edit7.text:=e1;

FGIntToBase10String(d,d1);

edit8.text:=d1;

FGIntToBase10String(n,n1);

edit9.text:=n1;

FGIntToBase10String(phi,nil1);

edit10.text:=nil1;

FGIntDestroy(phi);

 

FGIntDestroy(nilgint);

 

 

FGIntDestroy(p);

FGIntDestroy(q);

FGIntDestroy(dp);

FGIntDestroy(dq);

FGIntDestroy(e);

FGIntDestroy(d);

FGIntDestroy(n);

end;

 

 

procedure TForm1.Button3Click(Sender: TObject);

var

test,s,b64:string;

e,n:tfgint;

stin,ms:integer;

begin

test:=edit11.text;

Base10StringToFGInt(edit7.Text, e);

Base10StringToFGInt(edit9.text, n);

RSAEncrypt(test, e, n, test);

edit13.Clear;

ConvertBase256to64(test,b64);

//stin:=length(test) div 10;

//ms:=length(test) mod 10;

//s:=

edit13.lines.Add(b64);

 

FGIntDestroy(e);

FGIntDestroy(n);

 

end;

 

procedure TForm1.Button4Click(Sender: TObject);

var

test,b64:string;

d,n,nilgint:tfgint;

begin

test:=edit13.text;

ConvertBase64to256(test,b64);

test:=”;

Base10StringToFGInt(edit8.Text, d);

Base10StringToFGInt(edit9.text, n);

RSADecrypt(b64, d, n, Nilgint, Nilgint, Nilgint, Nilgint, test);

edit11.text:=test;

FGIntDestroy(d);

FGIntDestroy(n);

FGIntDestroy(nilgint);

end;

 

procedure TForm1.Button5Click(Sender: TObject);

begin

edit11.clear;

edit13.clear;

end;

 

procedure TForm1.Button6Click(Sender: TObject);

var

a,b,c:tfgint;

ss:string;

begin

Base10StringToFGInt(edit1.Text,a);

Base10StringToFGInt(edit2.Text,b);

FGIntModInv(a,b,c);

FGIntToBase10String(c,ss);

 

FGIntDestroy(a);

FGIntDestroy(b);

FGIntDestroy(c);

 

end;

 

end.

 

 

end.

 

Conclusion

By encrypting the arbitrary message using secret key cryptography with a public/private key pair, it assures the confidentiality of the message.

Compile environment: Delphi 7

 

 

Part 2

Message Confidentiality Practice

This demo made a simple implementation of Message Confidentiality. It encrypt/decrypt an arbitrary message using secret key cryptography, including Base64 encoding.

Author: Jing Ba jingb@kth.se

 

The process of operation:

1. Input the arbitrary message:


 

2. Click “Base64 Ecryption” and get the Ciphertext(record the ciphertext):


3. Input the record ciphertext or delete the plaintext and click “Base64 Decryption”:


 

4. We get the plaintext:


 

The main source code is as follows:

unit Unit1;

 

interface

 

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls;

 

type

TForm1 = class(TForm)

Button1: TButton;

Button2: TButton;

Edit1: TEdit;

Edit2: TEdit;

Label1: TLabel;

Label2: TLabel;

procedure Button1Click(Sender: TObject);

procedure Button2Click(Sender: TObject);

procedure FormCreate(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

 

var

Form1: TForm1;

function Base64Encode(const s: string): string;

function Base64Decode(const s: string): string;

implementation

 

{$R *.dfm}

 

function Base64Encode(const s: string): string;

var

i,c1,c2,c3: Integer;

m,n: Integer;

const

Base64: string = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/’;

begin

Result := ”;

m:=1;

n:=0;

for i := 1 to (Length(s) div 3) do

begin

c1 := Ord(s[m]);

c2 := Ord(s[m+1]);

c3 := Ord(s[m+2]);

m:=m+3;

Result := Result+base64[(c1 shr 2)and $3F+1];

Result := Result+base64[((c1 shl 4)and $30) or ((c2 shr 4)and $0F)+1];

Result := Result+base64[((c2 shl 2)and $3C) or ((c3 shr 6)and $03)+1];

Result := Result+base64[c3 and $3F+1];

n:=n+4;

if(n = 76)then

begin

n:=0;

Result := Result+#13#10;

end;

end;

if (Length(s) mod 3)=1 then

begin

c1 := Ord(s[m]);

Result := Result+base64[(c1 shr 2)and $3F+1];

Result := Result+base64[(c1 shl 4)and $30+1];

Result := Result+’=’;

Result := Result+’=’;

end;

if (Length(s) mod 3)=2 then

begin

c1 := Ord(s[m]);

c2 := Ord(s[m+1]);

Result := Result+ base64[(c1 shr 2)and $3F+1];

Result := Result+ base64[((c1 shl 4)and $30) or ((c2 shr 4)and $0F)+1];

Result := Result+base64[(c2 shl 2)and $3C+1];

Result := Result+ ‘=’;

end;

end;

 

function Base64Decode(const s: string): string;

var

i,m,n: Integer;

c1,c2,c3,c4: Integer;

const

Base64: string = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/’;

begin

Result := ”;

n:=1;

m:=Length(s);

if s[m]=’=’then m:=m-1;

if s[m]=’=’then m:=m-1;

for i:=1 to m div 4 do

begin

c1:=Pos(s[n],Base64)-1;

c2:=Pos(s[n+1],Base64)-1;

c3:=Pos(s[n+2],Base64)-1;

c4:=Pos(s[n+3],Base64)-1;

n:=n+4;

Result:=Result+Chr(((c1 shl 2)and $FC)or((c2 shr 4)and $3));

Result:=Result+Chr(((c2 shl 4)and $F0)or((c3 shr 2)and $0F));

Result:=Result+Chr(((c3 shl 6)and $C0)or c4);

end;

if m mod 4=2 then

begin

c1:=Pos(s[n],Base64)-1;

c2:=Pos(s[n+1],Base64)-1;

Result:=Result+Chr(((c1 shl 2)and $FC)or((c2 shr 4)and $3));

end;

 

if m mod 4=3 then

begin

c1:=Pos(s[n],Base64)-1;

c2:=Pos(s[n+1],Base64)-1;

c3:=Pos(s[n+2],Base64)-1;

Result:=Result+Chr(((c1 shl 2)and $FC)or((c2 shr 4)and $3));

Result:=Result+Chr(((c2 shl 4)and $F0)or((c3 shr 2)and $0F));

end;

 

end;

 

procedure TForm1.Button1Click(Sender: TObject);

begin

Edit2.Text :=Base64Encode(Edit1.Text);

end;

 

procedure TForm1.Button2Click(Sender: TObject);

begin

Edit1.Text :=Base64Decode(Edit2.Text);

end;

 

procedure TForm1.FormCreate(Sender: TObject);

begin

 

end;

 

end.

 

 

Conclusion

By encrypting the arbitrary message using secret key cryptography with Base64 encoding, it assures the confidentiality of the message.

Compile environment: Delphi 7

Security for Java and E-commerce Environments

Click here to download code (NB: You should register first)

[download id=”6″]

 

Assignment 5 (Client/Server Message Security)

Purpose: Develop an AC module to login users and accept their (typed) message. The module should comprehensively protect the message using a combination of secret and public key cryptography. Channel protection should be provided by the SSL (through JSSE), message protection by the PKCS#7 or S/MIME formats.

 

Client/Server

1. Operate server:


2. Register for users:


 

3. Login:


 

4. Chat (message transfer)


Main code:

1. AppServer.java

//Code for the connect class

class Connect

{

ObjectOutputStream streamToClient;

int ctr=0;


BufferedReader streamFromClient;


static
Vector
vector;

static
Vector
vctrList;

String message=” “;

static String str=new String(“UsrList”);

 

static

{


vector=new
Vector(1,1);

vctrList=new
Vector(1,1);

vctrList.addElement((String)str);

}

 

 

int verify(String mesg)

{


try

{

RandomAccessFile RAS=new RandomAccessFile(“UsrPwd.txt”, “r”);

int
i=0;

String str=””;

while((RAS.getFilePointer())!=(RAS.length()))

{

str=RAS.readLine();

if(str.equals(mesg))

{

ctr=1;

break;


}

}

RAS.close();

}

catch(Exception e)

{


}


return ctr;


 

}//end of verify()

 

2. clientInt.java

class TimerAction implements ActionListener

{

Socket toServer;

ObjectInputStream streamFromServer;

PrintStream streamToServer;

public
void actionPerformed(ActionEvent e2)

{

 

try

{

toServer=new Socket(“machine-name”,1001);

streamFromServer=new ObjectInputStream(toServer.getInputStream());

streamToServer=new PrintStream(toServer.getOutputStream());

message=txtMsg.getText();


//send a message to the server

streamToServer.println(“From Timer”);


//receive vectors from the server

Vector vector=(Vector)streamFromServer.readObject();

Vector vector1=(Vector)streamFromServer.readObject();


//show the online users

txtListUsers.setText(“”);

for(int j=1;j<vector1.capacity();j++)

{

txtListUsers.append((String)vector1.elementAt(j));

txtListUsers.append(“\n”);

}


//show the messsages

int i=messageCount;

for(;i<vector.capacity();i++)

{

 

txtMessages.append((String)vector.elementAt(i));

txtMessages.append(“\n”);


}

messageCount=i;

}//end of try

 

catch(Exception e)

{

System.out.println(“Exception “+e);

}

 

}//end of actionPerformed

}//end of TimerListener class

 

3.
Register.java

public
void actionPerformed(ActionEvent e1)

{

 

JButton button=(JButton)e1.getSource(); //get the source of the event

if(button.equals(btnCancel))

{

this.dispose();

}

else

{

int ver=verify(); //call the verify()

if(ver==1)

{


try

{

//establish a socket connection and create I/O socket streams

toServer=new Socket(“machine-name”,1001);

streamFromServer=new ObjectInputStream(toServer.getInputStream());

streamToServer=new PrintStream(toServer.getOutputStream());

 

//send a message to server for Registration

streamToServer.println(“RegisterInfo”);

usrName=txtUserName.getText();

usrPwd=txtUsrPwd.getPassword();

String pwd=new String(usrPwd);

 

//send the user name and password to the server

streamToServer.println(usrName+”:”+pwd);

 

//read the response from the server

String frmServer=(String)streamFromServer.readObject();

if(frmServer.equals(“Registered”))

{

new Login();

this.dispose();

}

else
if(frmServer.equals(“User Exists”))

{


showUsrExists(); //show error message

}

 

}//end of try

catch(Exception e)

{

System.out.println(“Exception “+e);

}

}//end of if

 

}//end of else

}//end of actionPerformed()

 

4. Login.java

public
void actionPerformed(ActionEvent e1)

{

JButton button=(JButton)e1.getSource();

if(button.equals(btnCancel))

{

this.dispose(); //close the current frame

}

else
if(button.equals(btnRegister))

{

new Register(); //call Register program

this.dispose();

}

else

{

 

try

{

//create socket and input-output socket streams

toServer=new Socket(“machine-name”,1001);

streamFromServer=new ObjectInputStream(toServer.getInputStream());

streamToServer=new PrintStream(toServer.getOutputStream());

 

//send message to server for login

streamToServer.println(“LoginInfo”);

UsrName=txtUsrName.getText();

UsrPwd=txtUsrPwd.getPassword();

strPwd=new String(UsrPwd);

 

//send the user name and password to the server

streamToServer.println(UsrName+”:”+strPwd);


//read the message from the server

String frmServer=(String)streamFromServer.readObject();


if(frmServer.equals(“Welcome”))

{

new clientInt(UsrName); //start the chat screen

this.dispose();

}

else

{

showdlg();//show error message

}

 

}//end of try

catch(Exception e)

{

System.out.println(“Exception Occured: “+e);

}

}//end of if..else

}//end of actionPerformed

 

SSL through JSSE

Simple client/sever includes SimpleSSLServer and SimpleSSLClient. We should configure KeyStore and TrustStore files before we operate the program.

We use keytool to generate KeyStore, clientStore and serverstore which contain the authorization for A, B and Server.

Establish authorization for Bob:


Check the authorization:


Generate certificate:


Export the certificate:


File list:


Operate server:


Operate client:


 

PKCS#7 implementation

Use java Security package. There is no PKCS#7 for digital signature in jdk. So we use BASE64 code as follows: