Java Security James Atlas August 5, 2008. James Atlas - CISC3702 Review Java 3D Java 3D Java Media...
-
date post
20-Dec-2015 -
Category
Documents
-
view
224 -
download
0
Transcript of Java Security James Atlas August 5, 2008. James Atlas - CISC3702 Review Java 3D Java 3D Java Media...
Java SecurityJava Security
James AtlasJames Atlas
August 5, 2008August 5, 2008
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 22
ReviewReview
• Java 3DJava 3D
• Java Media Framework (Sound)Java Media Framework (Sound)
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 33
ScheduleSchedule• TodayToday
Java SecurityJava Security• JVM SecurityJVM Security
• Java CryptographyJava Cryptography
• ThursdayThursday Java Garbage CollectionJava Garbage Collection Java BytecodeJava Bytecode
• TuesdayTuesday ReviewReview
• ThursdayThursday Final (5-7PM)Final (5-7PM)
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 44
Computer Security OverviewComputer Security Overview
• ThreatsThreats Secrecy attacks:Secrecy attacks: Attempts to steal confidential
information Integrity attacks:Integrity attacks: Attempts to alter information with some
selfish or malicious intent Availability attacks:Availability attacks: Attempts to disrupt a system's
normal operations
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 55
Computer Security OverviewComputer Security Overview
• Attack examplesAttack examples A brute force attackbrute force attack typically involves searching every
key until the right one unlocks the door. While that may seem like an expensive operation, in reality it is possible to preen the search using specialized tools.
A Trojan horse attackTrojan horse attack involves planting an enemy as an insider in such a way that it's not apparently noticeable. A computer virus serves as a common Trojan horse example.
A person-in-the-middleperson-in-the-middle attack intercepts communication between two parties without their knowledge. They assume that they're communicating normally.
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 66
Computer Security OverviewComputer Security Overview
• Defense examplesDefense examples FirewallsFirewalls CryptographyCryptography
• ConfidentialityConfidentiality AuthenticationAuthentication IntegrityIntegrity Nonrepudiation (proof of origin)Nonrepudiation (proof of origin) AuditingAuditing
• Policy - access controlPolicy - access control
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 77
Java Security HistoryJava Security History
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 88
JDK 1.0 Security ModelJDK 1.0 Security Model
Sandbox
Java Virtual MachineLocal Code
Remote Code
Local Host System Resources
(File System, Sockets, Printers…)
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 99
JDK 1.1 Security ModelJDK 1.1 Security Model
Sandbox
Java Virtual MachineLocal Code
Remote Untrusted Code
Local Host System Resources
(File System, Sockets, Printers…)
Remote Trusted Code
Full Access Limited Access
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 1010
JDK 1.2 Security ModelJDK 1.2 Security Model
Sandbox
Java Virtual Machine
Local Host System Resources
(File System, Sockets, Printers…)
Full Access Limited Access
Security Policy Class Loader
All Code
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 1111
New in Java 1.4New in Java 1.4
• Separate packages that are now included as part of JDKSeparate packages that are now included as part of JDK
JCE - Java Cryptography classesJCE - Java Cryptography classes JSSE - Java Secure Sockets ExtensionJSSE - Java Secure Sockets Extension JAAS - Java Authentication and Authorization ServicesJAAS - Java Authentication and Authorization Services Java GSS API - Java Generic Security Services APIJava GSS API - Java Generic Security Services API Java Certification Path APIJava Certification Path API
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 1212
The basic securityThe basic security architecture architecture• Java security (APIs)Java security (APIs)
((accessaccess): The Security manager): The Security manager ((originorigin): Signed Codebases): Signed Codebases ((behalfbehalf): Principle-based access control (JAAS)): Principle-based access control (JAAS) cryptographycryptography
• JVM securityJVM security Class Class loadersloaders Class file Class file verificationverification process process JVMJVM intrinsicintrinsic security features security features
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 1313
Java securityJava security Security Manager and its APISecurity Manager and its API• Central instance for access control as far as Central instance for access control as far as codecode
is concernedis concerned
• Policies define access to outer-domain resources Policies define access to outer-domain resources
• SecurityManager objects instances enforce SecurityManager objects instances enforce policies, throwing SecurityExceptionspolicies, throwing SecurityExceptions
• By default java programs do not have a security By default java programs do not have a security manager, therefore it is a good precaution to manager, therefore it is a good precaution to instantiate oneinstantiate one System.setSecurityManager(new SecurityManager())System.setSecurityManager(new SecurityManager()) java -Djava.security.manager java -Djava.security.manager
-Djava.security.policy=pURL SomeApp -Djava.security.policy=pURL SomeApp
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 1414
Java securityJava security Security Manager and its APISecurity Manager and its API• Fine-grained control to Limit access on:Fine-grained control to Limit access on:
SocketConnections (create, accept, multicast)SocketConnections (create, accept, multicast) Thread GroupsThread Groups Dynamic Library Loading (JNI)Dynamic Library Loading (JNI) Files (read, write, delete)Files (read, write, delete) Access to External shared ressources (printjob, Access to External shared ressources (printjob,
clipboard)clipboard) Program control (exit, toplevelwindow)Program control (exit, toplevelwindow) Runtime components (member, package, classloader)Runtime components (member, package, classloader)
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 1515
Policy File ExamplePolicy File Examplegrant signedBy "signer_names", codeBase "URL",grant signedBy "signer_names", codeBase "URL",
principal principal_class_name "principal_name",principal principal_class_name "principal_name",
principal principal_class_name "principal_name",principal principal_class_name "principal_name",
... {... {
permission permission_class_name "target_name", "action", permission permission_class_name "target_name", "action",
signedBy "signer_names";signedBy "signer_names";
permission permission_class_name "target_name", "action", permission permission_class_name "target_name", "action",
signedBy "signer_names";signedBy "signer_names";
......
};};
grant codebase "http://www.games.com",grant codebase "http://www.games.com",
signedBy "Duke",signedBy "Duke",
principal javax.security.auth.x500.X500Principal "cn=Alice" {principal javax.security.auth.x500.X500Principal "cn=Alice" {
permission java.io.FilePermission "/tmp/games", "read, write";permission java.io.FilePermission "/tmp/games", "read, write";
};};
• See http://java.sun.com/j2se/1.4.2/docs/guide/security/PolicyFiles.htmlSee http://java.sun.com/j2se/1.4.2/docs/guide/security/PolicyFiles.html
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 1616
Java securityJava security Code Base AuthenticationCode Base Authentication• Java-Archives (JARs) store codebasesJava-Archives (JARs) store codebases
• Proof of Origin can be be achieved by signing the Proof of Origin can be be achieved by signing the jars jars
JAR
Cat.classDog.classBird.class
Privatekey
hash
sign
JAR
Signed hash
Cat.classDog.classBird.class
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 1717
Java securityJava security JAAS: Security based on principalsJAAS: Security based on principals• Enables login functionalityEnables login functionality
Username, passwordUsername, password Fingerprint Fingerprint ......
• Execution permitted/denied depending on the Execution permitted/denied depending on the identity who runs the codeidentity who runs the code Policy based access to functionalityPolicy based access to functionality Fine-grained permission handling possibleFine-grained permission handling possible
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 1818
JVM securityJVM securityintrinsic featuresintrinsic features• Non-continuous memory Non-continuous memory model, distinct data model, distinct data
areasareas Java stack frames (execution state)Java stack frames (execution state) Method area (bytecode storage)Method area (bytecode storage) Garbage-collected heap (object storage)Garbage-collected heap (object storage)
• Type-safe casting Type-safe casting • NoNo self-modifying self-modifying codecode• Automated garbage-collecting disallows explicit Automated garbage-collecting disallows explicit
free operationfree operation• Automatic Array bounds-checkingAutomatic Array bounds-checking prevents prevents
off-by-one and buffer overflow scenariosoff-by-one and buffer overflow scenarios
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 1919
JVM security JVM security Class loadersClass loaders• Classloaders load a classfile as byte array into the Classloaders load a classfile as byte array into the
JVMJVM• Can load from Can load from
file, file, network or network or dynamically generated byte array dynamically generated byte array Can even compile on the fly (so Java behaves like Perl) Can even compile on the fly (so Java behaves like Perl)
• Security featuresSecurity features Establishing name spacesEstablishing name spaces Enforcing separation of trusted system library code from Enforcing separation of trusted system library code from
user-supplied code via parent-delegationuser-supplied code via parent-delegation
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 2020
JVM security JVM security VerifierVerifier
• Task: check loaded classfile for integrityTask: check loaded classfile for integrity
• 4-step process4-step process 1st step: structural correctness1st step: structural correctness 2nd step: data type correctness2nd step: data type correctness 3rd step: bytecode checks3rd step: bytecode checks 4th step: symbolical references management 4th step: symbolical references management
(runtime)(runtime)
• Not enabled by default for apps (it is for Not enabled by default for apps (it is for Applets):Applets): java -verify SomeAppjava -verify SomeApp
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 2121
JVM
JVM
CA FE BA BE 00 03 00 2D00 13 07 00 17 12 30 11.. .. ..
JVM security JVM security Classfile verificationClassfile verificationpublic class Cat { void bite (int times) { ... }}
public class Cat { void bite (int times) { ... }}
.class public Dog
.method bite I
.invokestatic seekVictim
...
.end method
.end class
.class public Dog
.method bite I
.invokestatic seekVictim
...
.end method
.end class
CA FE BA BE 00 03 00 2D00 13 07 00 17 12 30 11.. .. ..
CA FE BA BE 00 03 00 2D00 13 07 00 17 12 30 11.. .. ..
VerifierVerifierPASS
1
PASS
1
PASS
2
PASS
2
PASS
3
PASS
3
PASS
4
PASS
4
ClassloaderClassloader
JAVACJAVAC
bytecode assemblerbytecode assembler
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 2222
The Verification Process The Verification Process Pass 1: Pass 1: Basic Structural checksBasic Structural checks• the classloader delivers byte arraythe classloader delivers byte array• Magic number = 0xCAFEBABE ? Magic number = 0xCAFEBABE ? • Version id: 1.1=45.3, 1.2=46.0, 1.3=47.0, 1.4=48.0Version id: 1.1=45.3, 1.2=46.0, 1.3=47.0, 1.4=48.0• All recognized attributes need to be in proper lengthAll recognized attributes need to be in proper length• The class file must not be truncated or have extra The class file must not be truncated or have extra
bytes at the endbytes at the end• The constant pool must not contain any The constant pool must not contain any
„„superficially unrecognizable informationsuperficially unrecognizable information““
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 2323
The Verification ProcessThe Verification ProcessPass 2: Pass 2: Check Context-Pool (CP) informationCheck Context-Pool (CP) information• final classes are not subclassed, and final methods final classes are not subclassed, and final methods
are not overridden. are not overridden.
• All classes (except java.lang.Object) must have a All classes (except java.lang.Object) must have a superclass. superclass.
• Check constraints for CP-entries: For example, Check constraints for CP-entries: For example, class references in the CP can be resolved via a class references in the CP can be resolved via a field to a string reference in the CP. field to a string reference in the CP.
• Checking that all field references and method Checking that all field references and method references in the CP must have legal names, references in the CP must have legal names, classes, and type signature.classes, and type signature.
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 2424
The Verification ProcessThe Verification ProcessPass 3Pass 3 : Bytecode verification : Bytecode verification
• Core part of verificationCore part of verification• Static constraints Static constraints
Checking maximal local variable count throughout Checking maximal local variable count throughout control flowcontrol flow
Checking control-flow correctness (branch always Checking control-flow correctness (branch always to start of instruction, not beyond end of code)to start of instruction, not beyond end of code)
all exception-handlers are valid (no partial overlap)all exception-handlers are valid (no partial overlap) ......
• Structural constraints Structural constraints Reachability : subroutines (scope), exception Reachability : subroutines (scope), exception
handlershandlers data-flow : Instances initialization and new objects, data-flow : Instances initialization and new objects,
stack sizestack size
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 2525
The Verification ProcessThe Verification ProcessPass 4Pass 4: delayed checks during runtime: delayed checks during runtime
• Verifies that currently executing class is Verifies that currently executing class is allowed to reference the given class.allowed to reference the given class.
• The first time an instruction calls a method, or The first time an instruction calls a method, or accesses or modifies a field, the verifier accesses or modifies a field, the verifier checks the following:checks the following: method or field classmethod or field class Method or field signatureMethod or field signature that the currently executing method has that the currently executing method has
access to the given method or fieldaccess to the given method or field
• insert „quick“ optimized instructionsinsert „quick“ optimized instructions
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 2626
Problems with Java securityProblems with Java securityWhat is still missingWhat is still missing• Checks in terms of hard and soft limits onChecks in terms of hard and soft limits on
memory allocation memory allocation
Thread activationThread activation
• Excessive memory usage and threading utilization Excessive memory usage and threading utilization often leads to often leads to Denial of Service Denial of Service problemsproblems
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 2727
Java CryptographyJava Cryptography
• java.security:java.security: message digestsmessage digests certificatescertificates
• Java Cryptography Extension (JCE)Java Cryptography Extension (JCE) EncryptionEncryption Key generation and agreementKey generation and agreement Message authentication codesMessage authentication codes
• Java Secure Sockets Extensions (JSSE)Java Secure Sockets Extensions (JSSE) Implements SSL programmaticallyImplements SSL programmatically
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 2828
Security provider architectureSecurity provider architecture• Java security consists of Java security consists of enginesengines and and algorithmsalgorithms
• An An engineengine is an operation that a programmer can is an operation that a programmer can perform; eg create a message digestperform; eg create a message digest
• An An algorithmalgorithm is a particular implementation of that is a particular implementation of that operation; eg MD5 or SHA for message digestsoperation; eg MD5 or SHA for message digests
• The security provider interface provides an easy The security provider interface provides an easy mechanism for substituting algorithms while leaving mechanism for substituting algorithms while leaving the basic operations unchangedthe basic operations unchanged
• Format:Format: engine.algorithmengine.algorithm
eg eg MessageDigest.SHAMessageDigest.SHA
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 2929
Security provider architectureSecurity provider architectureimportimport java.security.Provider; java.security.Provider;
importimport java.security.Security; java.security.Security;
importimport java.util.Enumeration; java.util.Enumeration;
publicpublic classclass ExamineSecurity { ExamineSecurity {
publicpublic staticstatic voidvoid main(String[] args) main(String[] args) throwsthrows Exception { Exception {
Provider[] p = Security.Provider[] p = Security.getProvidersgetProviders();();
forfor ( (intint i = 0; i < p. i = 0; i < p.lengthlength; i++) {; i++) {
System.System.outout.println(p[i]);.println(p[i]);
forfor (Enumeration e = p[i].keys(); e.hasMoreElements();) { (Enumeration e = p[i].keys(); e.hasMoreElements();) {
System.System.outout.println(.println("\t""\t" + e.nextElement()); + e.nextElement());
}}
}}
}}
}}
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 3030
Java support for cryptographyJava support for cryptography
• KeysKeys
• CertificatesCertificates
• Key managementKey management
• Message digestsMessage digests
• Secure message digestsSecure message digests
• Digital signaturesDigital signatures
• Encryption & decryptionEncryption & decryption
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 3131
Keys & certificates: recapKeys & certificates: recap
• Two kinds of keys: Two kinds of keys: secret (symmetric)secret (symmetric) public/private (asymmetric)public/private (asymmetric)
• Certificates can be used to authenticate Certificates can be used to authenticate public keys:public keys: Public keys usually transmitted as part of a Public keys usually transmitted as part of a
certificatecertificate
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 3232
IssuesIssues
• Key management and storageKey management and storage
• Self-certification?Self-certification?
• Hierarchy of trustHierarchy of trust
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 3333
Generation and import/export of Generation and import/export of keyskeys
generator
Key KeyPair
java.security.KeyPairGeneratorjavax.crypto.KeyGenerator
Key factory
encodedkey data
key specificationEg P=3, Q=4, …
java.security.KeyFactoryjavax.crypto.SecretKeyFactory
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 3434
The Key class hierarchies: a The Key class hierarchies: a partial viewpartial view
java.security.Key
PublicKey PrivateKey
java.security.interfaces.DSAKey
DSAPrivateKeyDSAPublicKey
RSAPrivateKey
RSAPrivateKeyCrt
RSAPublicKey
java.security.KeyPair
java.crypto.SecretKey
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 3535
Why so many?Why so many?
• Certain algorithms require methods to Certain algorithms require methods to access key generation parameters for exportaccess key generation parameters for export DSAKey: methods getP(), getQ(), getG()DSAKey: methods getP(), getQ(), getG()
• Certain algorithms have specific rolesCertain algorithms have specific roles DHKey: Diffie-Hellman key exchangeDHKey: Diffie-Hellman key exchange
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 3636
Example: generate/export key Example: generate/export key pairpairpublicpublic classclass Export { Export {
publicpublic staticstatic voidvoid main(String[] args) main(String[] args) throwsthrows Exception { Exception {
KeyPairGenerator kpg = KeyPairGenerator.KeyPairGenerator kpg = KeyPairGenerator.getInstancegetInstance(("DSA""DSA"););
kpg.initialize(512, kpg.initialize(512, newnew SecureRandomSecureRandom());());
KeyPair kp = kpg.generateKeyPair();KeyPair kp = kpg.generateKeyPair();
Class spec =Class spec =Class.Class.forNameforName(("java.security.spec.DSAPrivateKeySpec""java.security.spec.DSAPrivateKeySpec"););
KeyFactory kf = KeyFactory.KeyFactory kf = KeyFactory.getInstancegetInstance(("DSA""DSA"););
DSAPrivateKeySpec ks = DSAPrivateKeySpec ks = (DSAPrivateKeySpec)kf.getKeySpec(kp.getPrivate(), spec);(DSAPrivateKeySpec)kf.getKeySpec(kp.getPrivate(), spec);
FileOutputStream fos = FileOutputStream fos = newnew FileOutputStream( FileOutputStream("exportedKey""exportedKey"););
ObjectOutputStream oos = ObjectOutputStream oos = newnew ObjectOutputStream(fos); ObjectOutputStream(fos);
oos.writeObject(ks.getX());oos.writeObject(ks.getX());
oos.writeObject(ks.getP());oos.writeObject(ks.getP());
oos.writeObject(ks.getQ());oos.writeObject(ks.getQ());
oos.writeObject(ks.getG());oos.writeObject(ks.getG());
}}
}} Derived from: Oaks (2001)
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 3737
Distributing public keys: Distributing public keys: certificatescertificates• Recall that a key doesn’t provide any authentication of the Recall that a key doesn’t provide any authentication of the
ownerowner
• A digitally-signed document + public key doesn’t guarantee A digitally-signed document + public key doesn’t guarantee that the document came from Xthat the document came from X
• Certificates solve the problem. A Certificate Authority Certificates solve the problem. A Certificate Authority verifies the public keyverifies the public key
• However, anyone can obtain a basic level certificateHowever, anyone can obtain a basic level certificate
• Bootstrapping problem? Who verifies the certificate Bootstrapping problem? Who verifies the certificate containing the public key of the CA?containing the public key of the CA?
• Workable solution: provide public keys of main CAs (eg in Workable solution: provide public keys of main CAs (eg in browser or in Java implementation)browser or in Java implementation)
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 3838
Certificates in JavaCertificates in Java• java.security.cert.Certificatejava.security.cert.Certificate
byte[] getEncoded()byte[] getEncoded()
void verify(PublicKey pk)void verify(PublicKey pk)
publicKey getPublicKey()publicKey getPublicKey()
• java.security.cert.CertificateFactoryjava.security.cert.CertificateFactory
Certificate generateCertificate(InputStream is)Certificate generateCertificate(InputStream is)
• Imports a certificate (doesn’t generate from scratch)Imports a certificate (doesn’t generate from scratch)
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 3939
Certificates in JavaCertificates in Java publicpublic staticstatic voidvoid main(String[] args) main(String[] args) throwsthrows Exception { Exception {
FileInputStream fr = FileInputStream fr = newnew FileInputStream(FileInputStream("./resources/sample.cer""./resources/sample.cer"););
CertificateFactory cf = CertificateFactory.CertificateFactory cf = CertificateFactory.getInstancegetInstance(("X509""X509"););
X509Certificate c = (X509Certificate)cf.generateCertificate(fr);X509Certificate c = (X509Certificate)cf.generateCertificate(fr);
System.System.outout.println(.println("Certificate for: ""Certificate for: " + c.getSubjectDN()); + c.getSubjectDN());
System.System.outout.println(.println("issued by: ""issued by: " + c.getIssuerDN()); + c.getIssuerDN());
System.System.outout.println(.println("valid from: ""valid from: " + c.getNotBefore() + + c.getNotBefore() +
" to "" to " + c.getNotAfter()); + c.getNotAfter());
System.System.outout.println(.println("generated with: ""generated with: " + c.getSigAlgName()); + c.getSigAlgName());
}}
Derived from: Oaks (2001)
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 4040
Revoked certificatesRevoked certificates
• Expiration date is sometimes not sufficientExpiration date is sometimes not sufficient
• For immediate invalidation, need a Certificate For immediate invalidation, need a Certificate Revocation List (CRL)Revocation List (CRL)
• Not clear yet how CA issues CRL yetNot clear yet how CA issues CRL yet
• Support in Support in CertificateCertificate class class
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 4141
Key & certificate managementKey & certificate management
• keystore: file (or may be database) holding keystore: file (or may be database) holding keys and certificateskeys and certificates
• Alias: keystore-specific name for entityAlias: keystore-specific name for entity
• Distinguished name (DN): longer name for Distinguished name (DN): longer name for entity (but not guaranteed unique)entity (but not guaranteed unique) Usually includes common name; organisation; Usually includes common name; organisation;
location; state; countrylocation; state; country
• Manipulated using keytool or Manipulated using keytool or programmaticallyprogrammatically
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 4242
keytoolkeytool
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 4343
Secret key managementSecret key management
• Recall that in public key systems, the private Recall that in public key systems, the private key must be kept private, but that in secret key must be kept private, but that in secret key systems, the secret key must be sharedkey systems, the secret key must be shared
• Management problem!Management problem! Use non-electronic means to distributeUse non-electronic means to distribute Use public key encryption to send encrypted key Use public key encryption to send encrypted key
(eg SSL)(eg SSL) Use key agreement algorithmUse key agreement algorithm
• keytool doesn’t understand secret keyskeytool doesn’t understand secret keys
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 4444
importimport java.io.FileOutputStream; java.io.FileOutputStream;
importimport java.io.ObjectOutputStream; java.io.ObjectOutputStream;
importimport java.security.MessageDigest; java.security.MessageDigest;
publicpublic classclass Send { Send {
publicpublic staticstatic voidvoid main(String[] args) main(String[] args) throwsthrows Exception { Exception {
FileOutputStream fos = FileOutputStream fos = newnew FileOutputStream( FileOutputStream("test""test"););
MessageDigest md = MessageDigest.MessageDigest md = MessageDigest.getInstancegetInstance(("SHA""SHA"););
ObjectOutputStream oos = ObjectOutputStream oos = newnew ObjectOutputStream(fos); ObjectOutputStream(fos);
String data = String data = "Martins message""Martins message";;
bytebyte[] buf = data.getBytes();[] buf = data.getBytes();
md.update(buf);md.update(buf);
oos.writeObject(data);oos.writeObject(data);
oos.writeObject(md.digest());oos.writeObject(md.digest());
}}
}}
Message digestsMessage digestsupdate()update()
add data to add data to digestdigest
digest()digest()
compute compute digestdigest
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 4545
•Recall that to verify a message digest, must read in message Recall that to verify a message digest, must read in message and its digest, compute the digest, and compare the twoand its digest, compute the digest, and compare the two
isEqual()isEqual()
publicpublic classclass Receive { Receive {
publicpublic staticstatic voidvoid main(String[] args) main(String[] args) throwsthrows Exception { Exception {
FileInputStream fis = FileInputStream fis = newnew FileInputStream( FileInputStream("test.md""test.md"););
MessageDigest md = MessageDigest.MessageDigest md = MessageDigest.getInstancegetInstance(("SHA""SHA"););
ObjectInputStream ois = ObjectInputStream ois = newnew ObjectInputStream(fis); ObjectInputStream(fis);
String data = (String)ois.readObject();String data = (String)ois.readObject();
System.System.outout.println(.println("Got message: ""Got message: " + data); + data);
bytebyte[] buf = ([] buf = (bytebyte[])ois.readObject();[])ois.readObject();
md.update(data.getBytes());md.update(data.getBytes());
ifif (MessageDigest. (MessageDigest.isEqualisEqual(md.digest(), buf)) {(md.digest(), buf)) {
System.System.outout.println(.println("Message is valid""Message is valid"););
}}
elseelse { {
System.System.outout.println(.println("Message was corrupted""Message was corrupted"););
}}
}}
}}
Source: Oaks (2001)
August 5, 2008August 5, 2008 James Atlas - CISC370James Atlas - CISC370 4646
Example: EncryptionExample: Encryptionpublicpublic classclass Encrypt { Encrypt {
publicpublic staticstatic voidvoid main(String[] args) main(String[] args) throwsthrows Exception { Exception {
KeyGenerator kg = KeyGenerator.KeyGenerator kg = KeyGenerator.getInstancegetInstance(("DES""DES"););
Cipher c = Cipher.Cipher c = Cipher.getInstancegetInstance(("DES/CBC/PKCS5Padding""DES/CBC/PKCS5Padding"););
Key key = kg.generateKey();Key key = kg.generateKey();
c.init(Cipher.c.init(Cipher.ENCRYPT_MODEENCRYPT_MODE, key);, key);
bytebyte[] input = [] input = "Secret message""Secret message".getBytes();.getBytes();
bytebyte[] encrypted = c.doFinal(input);[] encrypted = c.doFinal(input);
bytebyte[] iv = c.getIV();[] iv = c.getIV();
IvParameterSpec ips = IvParameterSpec ips = newnew IvParameterSpec(iv); IvParameterSpec(iv);
c.init(Cipher.c.init(Cipher.DECRYPT_MODEDECRYPT_MODE, key, ips);, key, ips);
bytebyte[] output = c.doFinal(encrypted);[] output = c.doFinal(encrypted);
System.System.outout.println(.println("The string was: ""The string was: " + + newnew String(output)); String(output));
}}
}} Derived from: Oaks (2001)