cobol

cobol

Sunday, June 30, 2024

INCIBE: Nuevas normativas de 2024 de ciberseguridad para vehículos

Nuevas normativas de 2024 de ciberseguridad para vehículos
INCIBE (Instituto Nacional de Ciberseguridad)


La evolución tecnológica en el sector automotriz ha alcanzado un nuevo hito con la implementación de las regulaciones R155 y R156 de la Unión Europea, que entrarán en vigor el 1 de julio de 2024 en España. Estas normativas marcan un antes y un después en la ciberseguridad de los vehículos, estableciendo estándares rigurosos para fabricantes y proveedores.

¿Por qué son necesarias estas regulaciones?

La creciente integración de tecnologías digitales en los vehículos modernos ha creado nuevas vulnerabilidades. Sistemas que antes estaban aislados ahora están interconectados y expuestos a posibles ciberataques. Esta situación ha llevado a la UE a tomar medidas proactivas para garantizar la seguridad de los conductores y pasajeros en la era digital.

Desglose de las nuevas regulaciones:

1. R155: Gestión de la Ciberseguridad
   - Establece requisitos para la implementación de sistemas de gestión de ciberseguridad en vehículos.
   - Obliga a los fabricantes a identificar y mitigar riesgos potenciales.
   - Requiere la implementación de medidas de seguridad en todo el ciclo de vida del vehículo.

2. R156: Gestión de Actualizaciones de Software
   - Define procesos para la gestión segura de actualizaciones de software en vehículos.
   - Asegura que las actualizaciones no comprometan la seguridad o el rendimiento del vehículo.
   - Establece protocolos para la notificación y documentación de actualizaciones.

Impacto en la industria:

Estas regulaciones no solo afectan a los vehículos en sí, sino que también transforman la operativa de fabricantes y proveedores. Las empresas deberán:

- Implementar sistemas robustos de gestión de ciberseguridad.
- Desarrollar procesos de actualización de software seguros y eficientes.
- Realizar evaluaciones de riesgo continuas.
- Formar a su personal en las nuevas prácticas de ciberseguridad.

Desafíos y oportunidades:

La implementación de estas normativas presenta varios desafíos:

1. Adaptación tecnológica: Las empresas deberán invertir en nuevas tecnologías y procesos.
2. Formación del personal: Será necesario capacitar a los empleados en nuevas competencias de ciberseguridad.
3. Coordinación en la cadena de suministro: Fabricantes y proveedores deberán trabajar en estrecha colaboración para garantizar el cumplimiento.

Sin embargo, estas regulaciones también crean oportunidades:

1. Mejora de la seguridad: Vehículos más seguros frente a ciberataques.
2. Innovación: Impulso al desarrollo de nuevas tecnologías de seguridad.
3. Confianza del consumidor: Mayor confianza en la seguridad de los vehículos conectados.

Recomendaciones para fabricantes y proveedores:

1. Iniciar la adaptación lo antes posible para evitar problemas de cumplimiento.
2. Invertir en formación y tecnología de ciberseguridad.
3. Colaborar estrechamente con socios y proveedores para garantizar un enfoque integrado.
4. Realizar auditorías regulares de ciberseguridad.
5. Mantenerse actualizados sobre las mejores prácticas y amenazas emergentes.

Conclusión:

Las nuevas normativas R155 y R156 representan un paso significativo hacia la seguridad en la era de los vehículos conectados. Aunque su implementación supone desafíos, también ofrece la oportunidad de crear un ecosistema automotriz más seguro y confiable. Los fabricantes y proveedores que se adapten rápidamente a estos cambios no solo cumplirán con la normativa, sino que también se posicionarán a la vanguardia de la industria automotriz del futuro.

Este blog post proporciona una visión general de las nuevas regulaciones y sus implicaciones. Para obtener información más detallada sobre cómo cumplir con estos requisitos, se recomienda consultar la guía completa publicada por INCIBE.

Friday, October 2, 2020

DFIR Fridays 1: UHS

 Ryuk: Real life Deathnote




1. Get offline procedures in place. When a malware assault brings down a hospital’s data methods, it disrupts inside enterprise processes in addition to affected person care, usually forcing hospitals to divert sufferers to close by amenities and limiting entry to affected person information.

That makes healthcare cyberattacks a affected person security difficulty, stated John Riggi, the American Hospital Association’s senior adviser for cybersecurity and threat. Just final month, a affected person in Germany died after an ambulance was diverted from a hospital hit with ransomware, in what seems to be the first death ensuing from a ransomware assault.

“We consider any cyberattack against a hospital or health system a potential threat-to-life crime—not just an economic crime,” stated Riggi, who has argued the U.S. authorities ought to prosecute ransomware assaults at hospitals as such. “Any delay in treatment caused by a ransomware attack could have an adverse outcome for the patient.”

In the wake of UHS cyberattack, employees have been utilizing paper information to doc affected person care, resulting in challenges coordinating care and acquiring medical histories. Some UHS amenities have needed to divert ambulances and cancel surgical procedures, in response to the Wall Street Journal, and a few websites are experiencing longer wait occasions at emergency departments, in response to CBS News.

Miller acknowledged it takes longer to finish duties when methods are offline, however stated employees are following established downtime procedures. Downtime procedures are additionally used throughout pure disasters and upkeep on data methods, along with cyberattacks, so employees have had expertise with them, he stated.

2. Preserve the proof. In the wake of a cyberattack, executives usually residence in on how one can handle the intrusion and keep operations. But it is also vital to guard something that might be proof for an investigation, together with documenting any communication from hackers and never deleting suspicious or malfunctioning recordsdata.

UHS is at the moment investigating the incident.

Figuring out how and what to doc could be “tricky,” famous Lani Dornfeld, a healthcare lawyer at legislation agency Brach Eichler, so organizations ought to have IT specialists—both in-house employees or outdoors consultants—lined as much as present assist.

During an investigation, IT groups will analyze knowledge from methods and networks to find out if affected person knowledge was accessed or eliminated—and it is very important be capable to overview as a lot knowledge as potential, stated Tyler Hudak, a apply lead for incident response at cybersecurity agency TrustedSec who beforehand served as a workforce lead for Mayo Clinic’s safety operations middle.

“When I get into an incident response and start performing forensics, we want to see all the data that we can,” he stated.

Increasingly, hackers will not simply deploy ransomware to encrypt knowledge. They will take away knowledge from the system, after which threaten to launch it if the sufferer would not pay, he stated.

That usually entails hackers gathering knowledge they need to steal right into a central location in the community, after which transferring it directly—in order that’s one signal Hudak stated he seems to be for throughout a forensic overview.

3. Watch for ransomware. Ransomware has been wreaking havoc on healthcare amenities for years, and it is getting more sophisticated, specialists say. It’s unconfirmed what sort of malware was concerned in the cyberattack at UHS, however stories from workers have instructed the incident stems from a Ryuk ransomware assault, in response to BleepingComputer, a pc and cybersecurity information website.

Ryuk is a ransomware pressure that hackers have a tendency to make use of on giant, enterprise organizations, stated Ido Geffen, vice chairman of product at cybersecurity firm CyberMDX. He stated hackers deploying Ryuk will usually spend weeks infiltrating and spreading all through a corporation’s methods and gadgets, earlier than making a ransom demand.

Hackers are “taking their time,” Geffen stated.

Miller declined to share what sort of malware was concerned in the cyberattack and the way hackers had been in a position to deploy it into UHS’ methods, since the health system continues to be engaged on investigating the incident.

“We’re continuing to review the forensic evidence,” Miller stated. “We’re only a few days into this, so we’re just not ready to come to conclusions.”

4. Choose who to alert. Riggi beneficial hospitals coping with cyberattacks notify federal authorities—similar to the FBI and the Homeland Security Department—who may help with responding to the incident. Organizations aren’t required to inform the FBI after a cyberattack, however it’s “strongly recommended,” he stated.

If it is potential affected person data has been breached as outlined by HIPAA, UHS may even should notify the affected people, native media shops and HHS’ Office for Civil Rights.

Hospitals may additionally need to set up social media insurance policies as a part of incident response, Hudak stated. Public details about the UHS cyberattack first emerged on Reddit, the place workers posted about being unable to entry cellphone and digital methods. Knowing the place data is shared is a key element of responding to an assault, he stated.

Organizations have to “get ahead of the curve and control the information going out,” Hudak stated


Credit: modernhealthcare.com

Saturday, August 6, 2016

Proactive vs Reactive cyber security


Fantastic article by


Richard Steinberger,
Independent Security Consultant

Proactive vs. Reactive Security



Introduction

Most security professionals are aware of the two basic approaches used to deal with security vulnerabilities: proactive and reactive. Proactive approaches include all measures that are taken with the goal of preventing host-based or network-based attacks from successfully compromising systems. Reactive approaches are those procedures that organizations use once they discover that some of their systems have been compromised by an intruder or attack program (e.g., Code Red or Nimda).

Proactive Approaches

Every modern organization realizes the value of dedicating some resources to the prevention of expensive damages that will likely occur if such preventive measures are not taken. Banks use thick steel and concrete vaults with advanced electronic systems to prevent and detect break-ins. Many companies, from convenience stores to casinos, use cameras to record business activities, the idea being that cameras both deter theft and help identify perpetrators when thefts do occur. Some organizations have started using Intrusion Detection and Response Systems (IDRSes) to try to detect computer intrusions and then activate defensive measures when an attack is detected. All of these examples represent proactive approaches to securing a company's infrastructure.

Reactive Approaches

Just as every company takes some measures to prevent future business losses, each also has plans in place to respond to such losses when the proactive measures either were not effective, or did not exist. Reactive methods include Disaster Recovery Plans, use of private investigation services and loss recovery specialists, reinstallation of operating systems and applications on compromised systems, or switching to alternate systems in other locations. Having an appropriate set of reactive responses prepared and ready to implement is just as important as having proactive measures in place.

A difficult set of decisions needs to be made in deciding how much resources (time, money, people) to dedicate to proactive approaches and how much to reactive approaches. These decisions can be further complicated by decisions about whether to use in-house resources, or to outsource. The remainder of this paper discusses these issues and focuses specifically on computer and network technologies.

Proactive and Reactive Approaches for Networked Companies

Richard Pethia, the director of the CERT Coordination Center at Carnegie Mellon University, recently stated, "Today's commercial off-the-shelf [software] technology is riddled with holes. The sheer number of vulnerabilities is overwhelming organizations." Pethia is referring to several examples in the recent past. These include vulnerabilities that allowed viruses and worms (hereafter referred to as malware) and other manual and automated attacks to inflict damages costing hundreds of millions of dollars per occurrence. Specific examples are: LoveLetter, a worm that severely clogged mail servers and networks in 2000^; Code Red, an aggressive worm that attacked unpatched Microsoft web servers and defaced their main pages^; and most recently, Nimda, a worm that spread by several different methods including email and web protocols, and searched for as many as 16 separate vulnerabilities to attack.

Add to those examples the recent Distributed Denial of Service (DDOS) attacks, less serious but still expensive virus attacks, exploits directed at unpatched popular firewalls (e.g., Check Point, Cisco Pix), buffer overflows, directory traversal and other more obscure attacks against web servers, and the scope of the problem starts to become quite clear. Since it is unlikely that most software will improve significantly from the state Pethia describes ("riddled with holes"), the only possible approaches are to: 1) repair the holes as soon as vendors confirm vulnerabilities and release patches, and 2) be prepared to respond to successful attacks against systems that have not yet been patched.

Although not all system vulnerabilities are the result of exploitable software flaws, most of them are. Ronald Dick, chief of the National Infrastructure Protection Center (NIPC, a division of the FBI), stated that about 80% of the issues the NIPC responds to could have been prevented if system administrators had been able to "download a patch and repair their systems." Other sources of system vulnerabilities include misconfigurations, poorly trained staff, unexpected interactions between systems, stolen or improperly protected passwords, or even hardware failures.

There are two extremely important conclusions that may be drawn from the above discussion. The first is that regular patching of systems is the single most important thing an organization can do to help defend itself against network attacks. The second conclusion is that even the most aggressive, comprehensive approach to patching systems and keeping virus definition files up to date is not going to prevent every network attacker from successfully penetrating a company's network and inflicting damages. Therefore, organizations that want to be well defended against network attacks need to employ an optimal mix of proactive and reactive approaches.

Specific Proactive Methodologies

The single most important thing an organization can do to defend itself against network attacks and malware is to patch vulnerable systems. This task isn't nearly as easy as it sounds. Even medium-sized companies can have thousands of computers. Large companies can own tens of thousands of systems, running multiple operating systems and applications from several different vendors on systems located in dozens of locations.

Although the size of the task can be daunting, reasonable approaches can still be developed and - if senior management provides enough resources - implemented. The support of senior management is crucial, because without it there will simply never be enough money, staff or time to implement more than a minimally reactive and ultimately expensive strategy.

So what are the elements of an effective patching strategy? All of the following are important:

After installing a new system, install all recommended vendor security patches. Most vendors maintain a website that provides the necessary information. Be sure to apply patches to all third-party applications (e.g., web servers, mail servers) in addition to patching the operating system.

Subscribe to security-related email lists from vendors. Most major software vendors offer these subscriptions for free. Apply patches when recommended.

Subscribe to the CERT mailing list, accessible at http://www.cert.org. Apply patches as recommended.

Ensure that all Microsoft and Macintosh computers are running recent antivirus software and that automated processes are running to regularly update the virus definitions. It is particularly important that antivirus software be regularly updated on portable computers used by mobile workers. These staff members frequently connect to unprotected networks where the chances of a virus infection are higher than on their corporate LAN.

Maintain a database that keeps track of what patches have been applied to the organization's most important systems: the Internet-accessible systems, firewalls, internal routers, databases and back office servers. If time and money are available, expand this database to include all company systems: both desktops and notebooks.

Patching systems is a crucial part of a proactive strategy to defend against network attacks. However, there are other techniques that, when combined with patching, provide an even more effective defense. Two of these techniques are discussed below.

Automated Vulnerability Assessment

Even aggressive patching does not "immunize" systems against all network attacks. Some attackers focus on common misconfigurations or even mistakes that no amount of patching would counteract. In other cases, attackers may have identified vulnerabilities but vendors have yet to release a patch. Unless these additional vulnerabilities are discovered and addressed, they can be exploited through manual or automated attacks and cause very significant network damages.

The basic idea of automated vulnerability assessment is that one uses a program, or better yet, several programs, that are able to systematically scan remote systems and networks and identify security vulnerabilities. These programs can be very effective at discovering previously unknown system vulnerabilities. In fact, attackers use tools very similar to these to identify exposed vulnerabilities in their targets.

There are several sources of such programs today. Examples include: Nessus, SAINT, nmap, ISS, CyberCop, and BindView. Unfortunately, it can be difficult to use these programs. The programs themselves can be complex and not easy to configure^; the results can be difficult to interpret^; the programs themselves need to be regularly updated so they can scan for recently discovered vulnerabilities^; it can be difficult to find a place on the company network that truly represents an "Internet view" of the company network^; and also, any company staff member who performs vulnerability scans using these tools has an insider's knowledge of the network and may therefore overlook (or be forced to skip) systems that a hacker would focus on.

The recommended approach to automated network vulnerability assessment is to outsource. In practice this means hiring an outside company to perform the network scanning and then prepare a well-documented report (containing specific details on how to fix any detected vulnerabilities). Most of the Big 5 accounting firms offer this kind of service, but the price is high, and they often want to bundle many other services with a network security scan.

One of the best independent companies that offers network vulnerability scanning services is VIGILANTe. Their scanning service includes not only many tools they have developed themselves, but several other commercial and shareware tools like Nessus, CyberCop, nmap, and ISS. Their flagship scanning service, SecureScan NX, scans a network internally as well as externally.

When using an outsourced scanning service, it's important to have the scans performed at regular intervals. This is not just a one-time thing. Every company needs to decide on a "scan frequency" - how often to have the networks scanned for vulnerabilities. Once every 90 days is suggested as a reasonable minimum scan rate.

Regular vulnerability scanning along with diligent system patching can go a long way to providing a highly effective defense against system attackers.

Independent Security Audit

An important additional measure that organizations can take in order to create an even higher level of network security is to engage the services of a professional security consulting company. There are many companies that offer on-site consulting services, including all of the Big 5 accounting firms, and Vigilinx, @stake, Foundstone and lots of independent professional security auditors.

The advantage of an independent security audit is that when experienced security consultants visit a company and interview critical staff members, they can discover critical weaknesses in security processes (or, indeed, the lack of such processes). Independent security assessments also involve the use of manual and automated security tools. A complete report is delivered at the end of the audit.

A Security Policy

No discussion on proactive security would be complete without mentioning the security policy. While there are many topics that should be covered in such a policy, one of the most important concerns staff member use of computers and networks. Unless employees are given specific details on what is and is not permitted, they may inadvertently introduce a virus or worm into the network, or otherwise cause significant damage to system infrastructure.

A good source of information for companies wanting to improve their security policies may be found at: http://www.ietf.org/rfc/rfc2196.txt

Reactive Security

Although the title of this article is "Proactive Versus Reactive Security," the two approaches are really not mutually exclusive. Every organization needs to be prepared for successful attacks (also know as intrusions), virus and worm outbreaks, denial of service attacks, and even attacks by disgruntled employees with an insider's knowledge of the systems and networks. Given today's geopolitical environment, it has become critical for every organization to have a workable Disaster Recovery Plan (DRP) as well.

Of all the "bad things" that can happen on a company's networks, the most common and most expensive (historically) is the virus/worm outbreak. Such attacks can tie up networks, cripple mail servers and disable many individual PCs. It's beyond the scope of this article to discuss the specifics of a virus/worm reaction policy. Many of the popular commercial antivirus vendors provide some insights on their websites.

Conclusion

As we have seen, proactive and reactive security are not opposing forces. Every organization needs to find an appropriate balance between how many resources can be devoted to proactive measures designed to deter network attacks, and how much to devote to reacting to intrusions. However this balance is addressed, it is strongly recommended that every organization have an effective patching process in place, and have networks scanned using vulnerability assessment programs. Those are the two most important components of proactive security.

Thursday, May 7, 2015

Dos and DDoS


A denial of service (DoS) attack is a resource consumption attack that has the primary goal of preventing legitimate activity on a victimized system. A DoS attack renders the target unable to respond to legitimate traffic.
There are two basic forms of denial of service:
• Attacks exploiting a vulnerability in hardware or software. This exploitation of a weakness, error, or standard feature of software intends to cause a system to hang, freeze, consume all system resources, and so on. The end result is that the victimized computer is unable to process any legitimate tasks.
• Attacks that flood the victim’s communication pipeline with garbage network traffic. These attacks are sometimes called traffic generation or flooding attacks. The end result is that the victimized computer is unable to send or receive legitimate network communications.
In either case, the victim has been denied the ability to perform normal operations (services).
DoS isn’t a single attack but rather an entire class of attacks. Some attacks exploit flaws in operating system software, whereas others focus on installed applications, services, or protocols. Some attacks exploit specific protocols, including Internet Protocol (IP), Transmission Control Protocol (TCP), Internet Control Message Protocol (ICMP), and User Datagram Protocol (UDP).
DoS attacks typically occur between one attacker and one victim. However, they aren’t always that simple. Most DoS attacks employ some form of intermediary system (usually an unwilling and unknowing participant) to hide the attacker from the victim. For example, if an attacker sends attack packets directly to a victim, it’s possible for the victim to discover who the attacker is. This is made more difficult, although not impossible, through the use of spoofing.
Many DoS attacks begin by compromising or infiltrating one or more intermediary systems that then serve as launch points or attack platforms. These intermediary systems are commonly referred to as secondary victims. The attacker installs remote-control tools, often called bots, zombies, or agents, onto these systems. Then, at an appointed time or in response to a launch command from the attacker, the DoS attack is conducted against the victim. The victim may be able to discover zombied systems that are causing the DoS attack but probably won’t be able to track down the actual attacker. Attacks involving zombied systems are known as distributed denial-of-service (DDoS) attacks. Deployments of numerous bots or zombies across numerous unsuspecting secondary victims have become known as botnets.
Here are some countermeasures and safeguards against these attacks:
• Adding firewalls, routers, and intrusion detection systems (IDSs) that detect DoS traffic and automatically block the port or filter out packets based on the source or destination address
• Disabling echo replies on external systems
• Disabling broadcast features on border systems
• Blocking spoofed packets from entering or leaving your network
• Keeping all systems patched with the most current security updates from vendors.

Wednesday, April 8, 2015

 Java implement Data encryption standard (DES)

Program to implement Data encryption standard (DES)




import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.xml.bind.annotation.
adapters.HexBinaryAdapter;

public class DES {

  private Cipher cipher = null;
  private DESKeySpec keySpec = null;
  private SecretKeyFactory keyFactory = null;

  public String encrypt(String inputString,
        String commonKey) throws Exception {

    String encryptedValue = "";
    SecretKey key = getSecretKey(commonKey);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] inputBytes = inputString.getBytes();
    byte[] outputBytes = cipher.doFinal(inputBytes);
    encryptedValue = new HexBinaryAdapter().marshal(outputBytes);
    return encryptedValue;
  }

  public String decrypt(String encryptedString,
        String commonKey) throws Exception {
    String decryptedValue = "";
    encryptedString = encryptedString.replace(' ', '+');
    SecretKey key = getSecretKey(commonKey);
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] recoveredBytes = null;
    try {
      recoveredBytes =
          cipher.doFinal
            (new HexBinaryAdapter().unmarshal(encryptedString));
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  
    decryptedValue = new String(recoveredBytes);
    return decryptedValue;
  }

  private SecretKey getSecretKey(String secretPassword) {
    SecretKey key = null;
    try {
      cipher = Cipher.getInstance("DES");
      keySpec = new DESKeySpec
          (secretPassword.getBytes("UTF8"));
      keyFactory = SecretKeyFactory.getInstance("DES");
      key = keyFactory.generateSecret(keySpec);
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println
        ("Error in generating the secret Key");
    }
    return key;
  }

  public static void main(String[] args) {
    BufferedReader reader;
    reader = new BufferedReader
        (new InputStreamReader(System.in));
    DES des = new DES();
  
    try {
      System.out.println
      ("ENCRYPTION --------------------------------");
      System.out.print("Enter Plain Message: ");
      String input = reader.readLine();
    
      System.out.print("Enter Key: ");
      String key = reader.readLine();
      System.out.println();
    
      System.out.print("Encrypted Message: ");
      String encrypted = des.encrypt(input, key);
      System.out.println(encrypted);
      System.out.println();
      System.out.println();
    
      System.out.println
      ("DECRYPTION --------------------------------");
      System.out.print("Enter Encrypted Message: ");
      encrypted = reader.readLine();
    
      System.out.print("Enter Key: ");
      key = reader.readLine();
      System.out.println();

      System.out.print("Decrypted Message: ");
      String decrypted = des.decrypt(encrypted, key);
      System.out.println(decrypted);
      System.out.println();
    
    } catch (Exception e) {
      e.printStackTrace();
    }
  
  }

}


Output:
ENCRYPTION-----------------------------------------------------------------------------------------
enter plain message: hello world (f.e)
Enter key: DonkeyKongCountry
 Encrypted message: 18FCD0F55D04602E564E35C1BC1BC1107A

DECRYPTION:---------------------------------------------------------------------------------------
Enter Encrypted Message:
18FCD0F55D04602E564E35C1BC1BC1107A
Enter Key: DonkeyKongCountry
Decrypted Message: Hello World

Friday, April 3, 2015

Java program to implement AES (Advanced encryption standard) algorithm.




import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES {
  BufferedReader reader;
  final String IV = "AAAAAAAAAAAAAAAA";
  public static void main(String args[]) {
    AES aes = new AES();
    aes.go();
  }
  public AES() {
    reader = new BufferedReader
        (new InputStreamReader(System.in));
  }
  void go() {
    StringBuffer message = new StringBuffer();
    try {
      System.out.print("Enter Message: ");
      message.append(reader.readLine());
    
      while (message.length() % 16 != 0)
        message.append('\u0000');
    
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }
  
    StringBuffer key = new StringBuffer();
    try {
      System.out.print("Enter Key: ");
      key.append(reader.readLine());
    
      while (key.length() % 16 != 0)
        key.append('\u0000');
    
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }
  
    // Encryption
    byte[] cipher =
        encrypt(message.toString(), key.toString());
  
    System.out.print("Cipher: ");
    for (int i=0; i<cipher.length; i++)
      System.out.print((int)cipher[i]);
    System.out.println();
  
    // Invalid key
    //key.replace(0, 6, "ABCDEF");

  
    // Decryption
    String decrypted =
        decrypt(cipher, key.toString());
  
    System.out.println("Decrypted message: " + decrypted);
  }
  byte[] encrypt
    (String plain, String key) {
  
    byte[] encrypted = null;
  
    try {
      Cipher cipher =
          Cipher.getInstance
            ("AES/CBC/NoPadding", "SunJCE");
    
      SecretKeySpec sks =
          new SecretKeySpec(key.getBytes("UTF-8"), "AES");
    
      AlgorithmParameterSpec params;
      params = new IvParameterSpec(IV.getBytes("UTF-8"));
      cipher.init(Cipher.ENCRYPT_MODE, sks, params);
  
      encrypted = cipher.doFinal(plain.getBytes("UTF-8"));
    } catch (Exception e) {
      e.printStackTrace();
    }
  
    return encrypted;
  }
  String decrypt(byte[] ct, String key) {
    StringBuffer decrypted = new StringBuffer();
    try {
      Cipher cipher =
          Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
    
      SecretKeySpec sks =
          new SecretKeySpec(key.getBytes("UTF-8"), "AES");
    
      AlgorithmParameterSpec params;
      params = new IvParameterSpec(IV.getBytes("
UTF-8"));
      cipher.init(Cipher.DECRYPT_MODE, sks, params);
    
      String s = new String(cipher.doFinal(ct), "UTF-8");
      decrypted.append(s);
    } catch (Exception e) {
      e.printStackTrace();
    }
  
    for (int i=decrypted.length()-1; i>0; i--) {
      if (decrypted.charAt(i) == '\u0000')
        decrypted.deleteCharAt(i);
      else break;
    }
  
    return decrypted.toString();
  }
}



***F.E , Output:

Enter message: " Obeanie went up Tora Bora and ended up in Abotttabad, It took Yankee Doodle Doo and Big Brother 10 years and a fortune to figure it out. The singleness of purpose is imperative and the use of NSA's Prism doubtful. ."
 Enter key:JackRabbitMoab308

Cipher: 3224-48-107-24-112-6134-1234771101-48-82114-87-84-3512-19-117507-103427011567-3698-698248-548625587-25-56-65-69-546-5875-77563219

Decrypted message: Obeanie went up Tora Bora and ended up in Abotttabad, It took Yankee Doodle Doo and Big Brother 10 years and a fortune to figure it out. The singleness of purpose is imperative and the use of NSA's Prism doubtful.