Java Tutorial/Security/DESede — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:01, 1 июня 2010

Sealed Objects

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SealedObject;
public class MainClass {
  public static void main(String[] args) throws Exception {
    String creditCard = "1234567890";
    KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
    Key key = keyGenerator.generateKey();
    Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    SealedObject so = new SealedObject(creditCard, cipher);
    String unencryptedCreditCard = (String) so.getObject(key);
    System.out.println(unencryptedCreditCard);
  }
}





using the name DESede rather than TripleDES

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
public class MainClass {
  public static void main(String[] args) throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
    keyGenerator.init(168);
    Key key = keyGenerator.generateKey();
    Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] ciphertext = cipher.doFinal("text".getBytes("UTF8"));
    for (int i = 0; i < ciphertext.length; i++) {
      System.out.print(ciphertext[i] + " ");
    }
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decryptedText = cipher.doFinal(ciphertext);
    System.out.println(new String(decryptedText, "UTF8"));
  }
}
//-71 -27 -10 -67 -24 -37 -79 70 text