This documentation is archived and is not being maintained.

Security in Visual J#

Visual Studio .NET 2003
 

Krishnan Thazhathekalam
Visual Studio Team
Microsoft Corporation

July 2002

Summary: This paper briefly discusses security in Microsoft Visual J++ 6.0 and the Microsoft virtual machine for Java (MSJVM) as a background. It then introduces security on the .NET Framework and the common language runtime and later provides guidelines on upgrading Visual J++ 6.0 applications to Microsoft Visual J# .NET.

This paper also discusses security features of the .NET Framework, such role-based security and ASP.NET Web application security, which Visual J# developers can use when building newer applications that target the common language runtime. (15 printed pages)

Contents

Security in Visual J++ 6.0
.NET Framework Security
Security in Visual J++ 6.0 Applications Upgraded to Visual J#
Security in New Applications Written in Visual J#
Role-Based Security
ASP.NET Web Application Security
Cryptographic Services in the .NET Framework
Conclusion

Security in Visual J++ 6.0

The Java language provides many language features that make it difficult for an application developer to write harmful code, either by accident or by intention. These language features include bounds checking on arrays, disallowing pointers and pointer arithmetic, and allowing type conversions only between compatible types.

In addition to language semantics, Visual J++ 6.0 and the Microsoft virtual machine for Java (MSJVM) use three primary mechanisms to implement security and protect valuable resources on the computer from malicious programs:

  • Byte-code verifier
  • Class loader
  • Security manager

The byte-code verifier ensures that executing code in an untrusted class file does not crash the MSJVM, leave it in an undefined state, or cause the system to stop responding. It inspects the class file to ensure that the bytecodes of the class are valid; the code never overflows or underflows the virtual machine stack; local variables are not used before initialization; and that field, method, and class access control modifiers are respected. The byte-code verifier provides security against malicious code that may have been written by a developer with the intention of causing harm or against invalid output produced by a faulty compiler.

The class loader provides security by associating the classes that it loads with a unique namespace. The namespace of classes loaded by a particular class loader is isolated from the namespaces of classes loaded using other class loaders. Because trusted and untrusted classes are always loaded through separate class loaders, this reduces the possibility that an untrusted class can replace a trusted class and thereby cause a spoofing attack. This allows the MSJVM to determine the source of a given class and restrict the activities of the class accordingly.

The security manager provides a security "sandbox" that restricts the access that untrusted code may have to sensitive resources. Applications running in the MSJVM have no security manager installed by default and therefore are allowed to perform all operations, including accessing sensitive resources, such as files on the hard disk. To install a security manager, a developer must create a class that extends the abstract java.lang.SecurityManager class and set this class as the security manager using the java.lang.System.setSecurityManager method. The abstract SecurityManager class contains many methods with names that begin with the word 'check'. The methods in the JDK level 1.1.4 libraries call these methods before performing potentially sensitive operations. Based on the implementation of the check methods, the developer can implement a security policy for an application that causes the check methods to either fail and throw a security exception or successfully return without any issues. Throwing an exception prevents the methods in the JDK level 1.1.4 class libraries from accessing sensitive resources.

For applets that are run in Microsoft Internet Explorer, the browser automatically installs a security manager that restricts the operations that applets can perform. Applets are also not allowed to set their own security manager. Internet Explorer provides various security zones, each with varying permission levels, so that applets or other code downloaded from the network is given varying permissions based on the download location. These zones include 'My Computer', 'Local Intranet', 'Internet' and 'Restricted Sites'. Usually, code downloaded from the 'My Computer' zone is granted maximum permissions, and code from 'Restricted Sites' granted the least. Additionally, applets can be signed with an Authenticode certificate issued by a trusted entity so that they are granted additional permissions.

Visual J++ 6.0 also supports the com.ms.security, com.ms.security.auditing, and com.ms.security.permissions packages that allow developers to associate specific permissions to code. At run time, classes that access sensitive resources can demand that their callers have specific permissions in order to be able to access those resources.

The java.security Package

The java.security package provides classes and interfaces that support cryptographic operations like generating keys, signatures, and cryptographically strong random numbers. Many classes provided in this package are provider based. The classes define a programming interface to which applications may write. The implementations can then be written by third-party vendors and plugged in seamlessly as needed. Therefore, developers can take advantage of multiple provider-based implementations without having to add or rewrite code. A default implementation of the security provider is provided in the MSJVM.

For more information, see the Visual J++ 6.0 product documentation in the MSDN online library.

.NET Framework Security

The .NET Framework and the common language runtime provide a rich security framework that protects computers and applications from malicious programs and from attack through access by unauthorized users.

The common language runtime enables developers to write managed applications and services in the language of their choice. Compiler writers for these languages can implement language semantics that make it difficult to write applications that violate type-safety rules and cause harm to the computer on which they are run.

With the common language runtime, all language compilers emit managed code in the form of Microsoft Intermediate Language (MSIL). Before execution, MSIL has to be Just-In-Time (JIT) compiled to native code that is specific to the hardware on which it will run. As part of compiling MSIL to native code, MSIL must pass through a verification process enforced by the runtime.

Verification is a fundamental building block in the .NET Framework security system. Verification involves two components: verifying MSIL for type safety and validating that metadata in assemblies is correct. MSIL is checked for type safety, occurrences of stack underflow or overflow, correct use of the exception handling facilities, and object initialization. Type safety ensures that objects are safely isolated from one another and are therefore safe from inadvertent or malicious corruption. If the code does not pass verification, then an exception is thrown by the runtime when the code is executed. Metadata validation involves examining metadata tokens to see that they index correctly into the tables that they access and that indexes into string tables do not point at strings that are longer than the size of buffers that should hold them, thereby eliminating buffer overflow.

Verification is the first part of security on the runtime. The .NET Framework provides several additional mechanisms to protect computer systems from malicious code or users:

  • Code access security, which uses permissions to control the access that code has to protected resources and operations. It helps protect computer systems from malicious mobile code and provides a way to allow mobile code to run safely. (Code access security together with the policies that govern it are referred to as evidence-based security.)
  • Role-based security, which provides information needed to make decisions about what a user is allowed to do. These decisions can be based on the user's identity, the role membership, or both.
  • ASP.NET Web application security, which provides a way to control access to a site by comparing authenticated credentials (or representations of them) to Microsoft Windows NT file system permissions or to an XML file that lists authorized users, authorized roles, or authorized HTTP verbs.

The article An Overview of Security in the .NET Framework provides an introduction to security on the .NET Framework and common language runtime and discusses some of these topics in further detail. More specific and detailed information is also available at .NET Framework Security.

Code Access Security

The .NET Framework provides code access security, a security mechanism that protects computer systems from malicious mobile code, allows users to run code from unknown origins safely, and protects trusted code from intentionally or accidentally compromising security. All managed code that targets the common language runtime, including applications and services written in Visual J#, receive the benefits of code access security, without the code having to make even a single code access security method call.

Code access security enforces security by restricting the operations that untrusted code can perform, such as access to protected resources, based on evidence presented by the code when it is loaded by the runtime. Evidence includes entities like the Web site or URL that the code was downloaded from or the strong name or Authenticode certificate of the code's publisher. Under code access security, an application can access protected resources, such as files on the computer, only if it is granted enough permission by the runtime based on evidence presented by it. The .NET Framework security policy examines the evidence presented by the application and then, based on the security policy on the computer, grants specific permissions to the code. Applications will only be allowed to perform those operations that they have permissions for. Thus, under default security policy, fully trusted libraries loaded from the hard disk of the computer would be granted all permissions (and therefore, access to all resources), while untrusted code downloaded from the Internet would only be granted a limited set of permissions.

At run time, when an application tries to invoke a. NET Framework method that accesses a sensitive resource, the runtime walks up the stack to verify if all the callers on the stack have the appropriate permission to access the resource. If all callers have the required permissions, the stack walk succeeds and the operation is allowed or else a security exception is thrown.

Figure 1. Security Stack Walk

For more information, see Code Access Security.

Security in Visual J++ 6.0 Applications Upgraded to Visual J#

Like all applications and services that target the common language runtime, applications written in Visual J# follow the security semantics of the .NET Framework and common language runtime. This applies to new applications written in Visual J# that target the .NET Framework class libraries, as well as existing Visual J++ 6.0 applications that have been upgraded to Visual J#. This section discusses how the various security mechanisms in the .NET Framework map to those in Visual J++ 6.0 and provides application developers with guidelines on upgrading their existing Visual J++ 6.0 applications to Visual J#.

Because applications and services created in Visual J# are written using the Java language, Visual J# offers the same language benefits as Visual J++ 6.0. This means that, like Visual J++ 6.0, Visual J# enforces bounds checking on arrays, disallows pointers and pointer arithmetic, and allows type conversions only between compatible types.

The Visual J# compiler compiles Java language source code to MSIL. As discussed in the .NET Framework Security section, when the runtime performs a JIT compilation on MSIL to native code, it is also verified for type-safety and metadata correctness. This ensures that malicious code that violates type-safety rules is not allowed to run.

Accessing JDK Level 1.1.4, WFC and com.ms.* Class Libraries

By default, for strong-named assemblies, the .NET Framework applies declarative security to all publicly accessible methods, properties, and events of the assembly to restrict their use to fully trusted callers. For details, see Version 1 Security Changes for the Microsoft .NET Framework.

Because the Visual J# class libraries are strong named and installed to the Global Assembly Cache, only fully trusted applications can access the classes in the JDK level 1.1.4, Windows Foundation Classes (WFC), and com.ms.* packages. Under the default security policy of the .NET Framework, this means that only applications that are loaded from the hard disk or run in a code group to which policy has granted the FullTrust permission set can access these classes. Attempting to access these classes from a partially trusted application, such as one downloaded from the Internet or run from a remote location, will result in a security exception.

Developers can still build fully trusted libraries on top of the classes in Visual J# and expose them to partially trusted code. Developers of these libraries are responsible for ensuring that the libraries are fully secure and that the libraries do not leave the machine vulnerable to exploits. A secure library is a class library that uses security demands to ensure that the library's callers have permission to access the resources the library exposes. For example, a secure class library might have a method for creating files that would demand that its callers have permissions to create files. For more information, see Writing Secure Class Libraries.

Many of the classes in Visual J# provide functionality equivalent to most of the JDK level 1.1.4 classes. These classes are designed to demand for appropriate .NET Framework permissions before performing sensitive operations. Therefore, in addition to requiring that the immediate callers of Visual J# libraries be fully trusted, a runtime check is also performed for specific permissions before access to a resource is allowed. As described under Code Access Security, the runtime walks up the stack to verify if all callers on the stack have the appropriate permission to access the resource. However, third-party libraries layered on top of Visual J# libraries can override the outcome of security checks by calling Assert, Deny or PermitOnly on these permission checks. As previously mentioned, in such cases, ensuring that the library does not leave the machine vulnerable to exploits is the responsibility of the library developer. For more information, see Overriding Security Checks.

Unlike the JDK level 1.1.4 classes, the classes in the WFC and com.ms.* packages do not perform any demands for .NET Framework permissions. The only security restriction is that the immediate callers of these classes must be fully trusted.

Class Loaders and Security Managers in Visual J#

Unlike Visual J++ 6.0, class loaders and security managers are not supported in Visual J#. When upgrading existing Visual J++ 6.0 applications that use custom class loaders or security managers, they must be modified to use the code access security semantics provided by the .NET Framework and common language runtime. For more information on .NET Framework code access security, see Code Access Security.

In Visual J#, the following methods in the class java.lang.SecurityManager are unsupported:

  • SecurityManager.classDepth
  • SecurityManager.classLoaderDepth
  • SecurityManager.currentClassLoader
  • SecurityManager.currentLoadedClass
  • SecurityManager.getClassContext
  • SecurityManager.inClass
  • SecurityManager.inClassLoader

These methods throw the com.ms.vjsharp.MethodNotSupportedException exception in Visual J#. Visual J# also does not support the methods java.lang.System.setSecurityManager and java.lang.System.getSecurityManager.

Similarly, the following methods in the class java.lang.ClassLoader are unsupported:

  • ClassLoader.defineClass
  • ClassLoader.resolveClass

These methods throw com.ms.vjsharp.MethodNotSupportedException in Visual J#. The method java.lang.Class.getClassLoader always returns null on Visual J#.

When upgrading an existing Visual J++ 6.0 application that implements a custom security manager, it must be modified to use the permission classes in the System.Security.Permissions namespace in the .NET Framework. Many of the 'check' methods in the java.lang.SecurityManager class have equivalent permission classes in the .NET Framework. The following example shows a simplistic security manager that illustrates how applications using security managers can be upgraded to Visual J#.

class MySecurityManager extends SecurityManager
{
   .
   .
   .
   public void checkDelete(String file)
   {
      if (file == "boot.ini")
         throw new SecurityException();
      return;
   }
   .
   .
}

In a class library or application, a developer would use this class as follows:

{
   SecurityManager sm;
   if ((sm = System.getSecurityManager()) != null)
      sm.checkDelete("boot.ini");
   
   // If the operation is not allowed, an exception is thrown in the
   // previous statement; Otherwise, checkDelete returns and execution
   // continues.
   .
   .
   // Go ahead and modify or delete the file.
   .
   .
}

The previous method can be modified as follows:

{   
FileIOPermission fd = new 
   FileIOPermission(FileIOPermissionAccess.Write, "boot.ini");
   fd.Demand();
   // If the operation is not allowed, an exception is thrown in the
   // previous statement; otherwise, the Demand method returns and execution
   // continues.

   .
   .
   // Go ahead and modify or delete the file.
   .
   .
}

The Demand method causes the runtime to verify if all callers that are higher in the call stack have the permission to access the specified file. If any callers in the stack do not have this permission, then a SecurityException is thrown thereby preventing the callers from accessing the protected resource. For more information on the permission classes available in the .NET Framework, see System.Security.Permissions Namespace.

In conjunction with modifying the application to use the .NET Framework permission classes, it may also be necessary to modify the .NET Framework security policy on the computer to get the desired effect. Whether a specific permission demand passes at runtime depends on the code group that the application runs in and the permissions granted by the runtime to that code group. For more information on administering the .NET Framework security policy, see General Security Policy Administration.

Custom class loaders extend java.lang.ClassLoader and override the loadClass method for their specific implementation. Applications that use custom class loaders must be appropriately modified to not use the ClassLoader.defineClass and ClassLoader.resolveClass methods. The applications need to be modified to use the .NET Framework classes to now load managed assemblies. Applications can use methods like Assembly.Load or Assembly.LoadFrom to load an assembly and then retrieve a specific type from the loaded assembly.

In Visual J++ 6.0, classes loaded by a class loader are associated with a unique namespace that is isolated from classes loaded by other class loaders. This ensured that a trusted class loaded by a specific class loader could not be spoofed by a less trusted and potentially malicious class loaded by another class loader (such as from the Internet). In the .NET Framework, the assembly forms the type boundary. Each type identity includes the name of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly. Therefore, classes from a trusted assembly cannot be spoofed with untrusted classes from an assembly downloaded from the Internet.

For more information, see Assemblies.

Upgrading Applications That Use Third-Party Security Providers

Visual J# supports the java.security package. Visual J# also provides a default security provider implementation that can be used for operations such as generating keys and signatures. In addition, Visual J# allows users to plug in third-party security providers that can be used instead of the default security provider. Users can specify, through a security configuration file, the security providers installed on the system, and the order in which the providers are to be searched for an algorithm implementation.

Visual J# users can use the configuration file vjsharp.config in the Microsoft Visual JSharp .NET\Framework\v<Visual J# version> directory to specify these settings. This is an XML file, and all the security settings are specified under the <security> tag of this file. The typical format of this file is as follows:

<vjsharpconfiguration>
   <security>
      <packageinfo> 
         <description>Description of the package</description>
            <loadinfo class="packageName.className, assemblyName,
             Version=assemblyVersion, Culture=assemblyCulture,
             PublicKeyToken=assemblyPublicKeyToken">
               <load/> (or <noload/>)
            </loadinfo>
      </packageinfo>
      .
      .
      .
   </security>
</vjsharpconfiguration>

The tags in the file are used as follows:

<packageinfo>
Specifies all the installed security providers.
<description>
Allows the user to provide a description of the package and plays no role in loading a provider.
<loadinfo>
Specifies the name of the provider class for the security provider package and assembly in which it is located. If only the assembly name is specified, only the ApplicationBase is used to locate the assembly. For assemblies installed to the global assembly cache, the other parameters such as assembly version, culture, and public key token must also be specified. If an assembly is not installed to the global assembly cache, you can also specify the fully qualified path to the assembly.
<load> or <noload>
Specify if the assembly should be loaded or ignored for the current search. Specifying <noload> causes it to be ignored.

vjsharp.config is not created by default during installation of Visual J# .NET. When no configuration file exists, the default security provider that is included with the Visual J# class libraries is used. To use a different provider, the vjsharp.config file must be created in the Microsoft Visual JSharp .NET\Framework\v<Visual J# version> directory. The format of the file should be as previously specified. The providers are loaded in the order in which they appear within the <security> tag. Errors encountered in the format of a <packageinfo> tag are silently ignored. The assemblies of the providers listed in this file must be installed to a location such that the .NET Framework common language runtime's assembly search heuristics for locating and loading assemblies can find them. When the vjsharp.config file is specified, the default provider is not searched unless specified in the file. A <loadinfo> tag for the default provider might look something like:

<loadinfo class="com.ms.vjsharp.security.provider.ms, vjslib, Version= 
1.0.3300.0, Culture=neutral, PublicKeyToken= b03f5f7f11d50a3a">
            <load/>
</loadinfo>

Security in New Applications Written in Visual J#

Applications and services written in Visual J# are subject to the same runtime restrictions as any other managed application that runs on the .NET Framework. When invoking the methods on .NET Framework classes, the runtime will verify that all callers on the stack, including any Visual J# applications, have appropriate permissions to perform the operation. An application written in Visual J# cannot access any code or resource for which the .NET Framework security policy on the computer does not grant permission.

A Visual J# application developer can also use the classes in the .NET Framework class libraries to specify permissions required for an application to run, demand specific permissions from callers, and specify permissions that must be denied to all callers of his classes. These requests will then be evaluated at runtime by the common language runtime to grant the set of permissions the executing application can have. A Visual J# application can also demand that its callers have specific permissions or possess a digital signature.

In addition to these semantics, all applications or components written using Visual J# must be fully trusted to be able to run. All components or applications compiled by the Visual J# .NET compiler hold references to Visual J# libraries. This applies to new applications written in Visual J# where only the .NET Framework class libraries are accessed as well as to existing Visual J++ applications upgraded to Visual J#. As the Visual J# class libraries are strong named and installed to the Global Assembly Cache, only fully trusted applications can access the classes in these assemblies. A security exception is thrown when a Visual J# application or service is run from a code group that has not been granted the FullTrust named permission set by security policy.

Therefore, the following elements need to be considered when writing applications using Visual J# .NET:

Applications

All applications executed from the local machine run in the MyComputer code group and are granted the FullTrust permission set under the default security policy of the .NET Framework. Therefore, Visual J# applications that are run from the local machine will run without security exceptions. However, applications that are run from remote locations such as a network share run in the Internet or Intranet code groups. Because applications run in these code groups are not granted the FullTrust permission set under the default security policy of the .NET Framework, they will fail with a security exception. If a Web application is mapped to a UNC share, then that share must be granted full trust using the common language runtime security policy management tools. For more information, see General Security Policy Administration and Code Groups.

Managed Controls Hosted in Internet Explorer

All managed controls that are hosted in Internet Explorer run in the Internet or Intranet code groups. Because components run in these code groups are not granted the FullTrust permission set under the default security policy of the .NET Framework, these Visual J# applications will fail with a security exception. This is especially true of WFC HTML controls upgraded to Visual J#.

When a Visual J# application is downloaded and run using the code download feature in Internet Explorer, the application runs in the Internet or Intranet code group. Because these code groups do not have the FullTrust permission set under the default security policy, the application will fail with a security exception.

To run Visual J# applications or components from remote locations, the Intranet, or the Internet, at least one of the following must be true:

  • The component or application must have been signed with a key pair and the .NET Framework security policy on the computer modified to grant the FullTrust named permission set to components or applications signed with this key pair.
  • The component or application must have been signed with an Authenticode certificate and the .NET Framework security policy on the computer modified to grant the FullTrust named permission set to components or applications signed with this Authenticode certificate.
  • The .NET Framework security policy on the computer has been modified to grant the FullTrust named permission set to controls downloaded from the Web site (URL) where the component or application is hosted.

Modifying the Security Policy of the MyComputer Code Group

When the security policy of the MyComputer code group is modified from the default level of FullTrust to a more restricted permission set, Visual J# applications that are started from the local machine cannot run.

Role-Based Security

This section provides a brief introduction to role-based security and classes in the .NET Framework that applications can use to implement role-based security. It also walks through a sample program that shows how a Visual J# developer can implement role-based security in an application.

Business applications often provide access to data or resources based on credentials supplied by the user. Typically, such applications check the role of a user and provide access to resources based on that role. The common language runtime provides support for role-based authorization based on a Windows account or a custom identity.

Roles are often used in financial or business applications to enforce policy. .NET Framework role-based security supports authorization by making information about the principal, which is constructed from an associated identity, available to the current thread. The identity (and the principal it helps to define) can be either based on a Windows account or be a custom identity unrelated to a Windows logon account. Applications can use role membership to determine whether a principal is authorized to perform a requested action. The .NET Framework provides role-based security support that is flexible and extensible enough to meet the needs of a wide spectrum of applications. You can choose to interoperate with existing authentication infrastructures, such as COM+ 1.0 Services, or to create a custom authentication system. Role-based security is particularly well-suited for use in ASP.NET Web applications, which are processed primarily on the server. However, .NET Framework role-based security can be used on either the client or the server. For more information, see Role-Based Security.

The System.Security.Principal and System.Security.Permissions namespaces in the .NET Framework contain the classes that managed applications can use to implement role-based security. All classes in these namespaces are fully accessible to applications and services written in Visual J#. The following is an example of a Visual J# program that uses the classes in the .NET Framework to implement role-based security:

import System.*;
import System.Threading.*;
import System.Security.Principal.*;

public class RoleBasedSecurity
{
   public static void main(String[] args)
   {
      // Get the current identity and put it into an identity object.
      WindowsIdentity MyIdentity = WindowsIdentity.GetCurrent();

      // Put the identity into a principal object.
      WindowsPrincipal MyPrincipal = new 
      WindowsPrincipal(MyIdentity);


      // Principal values.
      String Name = MyPrincipal.get_Identity().get_Name();
   String Type = 
MyPrincipal.get_Identity().get_AuthenticationType();
      boolean Auth = 
MyPrincipal.get_Identity().get_IsAuthenticated();

      // Identity values.
      String IdentName = MyIdentity.get_Name();
      String IdentType = MyIdentity.get_AuthenticationType();
      boolean IdentIsAuth = MyIdentity.get_IsAuthenticated();
      boolean ISAnon = MyIdentity.get_IsAnonymous();
      boolean IsG = MyIdentity.get_IsGuest();
      boolean IsSys = MyIdentity.get_IsSystem();
      String Token = MyIdentity.get_Token().ToString();

      // Print the values.
      Console.WriteLine("Principal Values for current thread:");
      Console.WriteLine("\n\nPrincipal Name: " + Name);
      Console.WriteLine("Principal Type: " + Type);
      Console.WriteLine("Principal IsAuthenticated: " + Auth);

      Console.WriteLine("\n\nIdentity Values for current thread:");
      Console.WriteLine("Identity Name: " + IdentName);
      Console.WriteLine("Identity Type: " + IdentType);
      Console.WriteLine("Identity IsAuthenticated: " + IdentIsAuth);
      Console.WriteLine("\n\nIdentity IsAnonymous: " + ISAnon);
      Console.WriteLine("Identity IsGuest: " + IsG);
      Console.WriteLine("Identity IsSystem: " + IsSys);
      Console.WriteLine("Identity Token: " + Token);
   }
}

ASP.NET Web Application Security

Most Web sites need to selectively restrict access to some portions of the site. ASP.NET, in conjunction with Internet Information Services (IIS), can authenticate user credentials such as names and passwords, using any of the following authentication methods:

  • Windows: basic, digest, or Integrated Windows Authentication (NTLM or Kerberos)
  • Microsoft Passport Authentication
  • Forms
  • Client Certificates

ASP.NET controls access to site information by comparing authenticated credentials (or their representations) to NTFS file system permissions or to an XML file that lists authorized users, authorized roles (groups), or authorized HTTP verbs. For more information, see ASP.NET Web Application Security.

ASP .NET Web applications that are written in Visual J# can use the classes in the System.Web.Security and System.Security.Principal namespaces of the .NET Framework to implement security for Web applications.

Cryptographic Services in the .NET Framework

Public networks such as the Internet do not provide a way for secure communication among entities. Communication over such networks is susceptible to being read or even modified by unauthorized third parties. Cryptography protects data from being viewed or modified and provides secure channels of communication over otherwise insecure channels. The .NET Framework provides many classes in the System.Security.Cryptography, System.Security.Cryptography.X509Certificates, and System.Security.Cryptography.Xml namespaces that support cryptographic operations.

The classes in the .NET Framework cryptography namespace manage many details of cryptography for the developer. All classes in the cryptographic namespaces in the .NET Framework are fully accessible to the Visual J# developer. The following sample demonstrates the use of cryptographic classes in a Visual J# program and uses the DESCryptoServiceProvider class and a specified Key and initialization vector to encrypt a file.

private static void EncryptData(String inFileName, String outFileName,
ubyte[] desKey, ubyte[] desIV) 
{    
   //Create the file streams to handle the input and output files.
   FileStream fin = new FileStream(inFileName, FileMode.Open, 
FileAccess.Read);
   FileStream fout = new FileStream(outFileName, FileMode.OpenOrCreate,
FileAccess.Write);
   fout.SetLength(0);

   //Create variables to help with read and write.
   ubyte[] bin = new ubyte[100]; // This is intermediate storage
for the encryption.
   long rdlen = 0; // This is the total number of bytes written.
   long totlen = fin.get_Length(); //This is the total length of the
                                   //input file.
   int len; //This is the number of bytes to be written at a time.
      
   DES des = new DESCryptoServiceProvider();          
   CryptoStream encStream = new CryptoStream(fout, 
des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
   Console.WriteLine("Encrypting...");

   //Read from the input file, then encrypt and write to the output file.
   while(rdlen < totlen)
   {
      len = fin.Read(bin, 0, 100);
      encStream.Write(bin, 0, len);
      rdlen = rdlen + len;
      Console.WriteLine(rdlen + " bytes processed");
   }
   encStream.Close();  
   fout.Close();
   fin.Close();
}

Conclusion

Visual J# allows Java-language developers to upgrade existing applications to the .NET Framework in a seamless manner while still ensuring that the upgraded applications are secure. It also allows developers to fully use the rich set of security services and class libraries provided by the common language runtime and the .NET Framework. These will fully enable developers to write Java-language applications that are secure and protected from malicious code and users.

Show: