[RESOLVIDO] Não acha algoritimo de criptografia

Salve galera!

O entalangment me passou uma classe e deu uma ajudona pra fazela funcionar através desta thread http://www.guj.com.br/posts/list/226191.java

a zica é q só funciona no eclipse… nem no prompt nem no jgrasp ela acha os algoritmos. No caso da chave ele não acha por exemplo o PBKDF2WithHmacSHA1 mas só o PBEWithMD5AndDES… depois desse não acha o AES/OFB/NoPadding nem a PKCS5Padding… mas no eclipse o treco roda… dae pensei q era problema de biblioteca, já q no eclipse eu tenho uma pá e também nao entendo do eclipse, então baixei da sun o arquivo q tem as bibliotecas jce1_2_2.jar e o sunjce_provider.jar, olhei nelas e elas tinham as classes utilizadas pela classe de criptografica, fiz as importações direto explícitas e nada!

os traces:
java.security.NoSuchAlgorithmException: No such algorithm: AES/OFB/NoPadding
at javax.crypto.Cipher.getInstance(DashoA13*…)
at javax.crypto.Cipher.getInstance(DashoA13*…)
at comuns.Cripto.cifrar(Cripto.java:48)
at comuns.Cripto.main(Cripto.java:92)

e o outro

java.security.NoSuchAlgorithmException: PBKDF2WithHmacSHA1 SecretKeyFactory not available
at javax.crypto.SecretKeyFactory.(DashoA13*…)
at javax.crypto.SecretKeyFactory.getInstance(DashoA13*…)
at comuns.Cripto.senha(Cripto.java:41)
at comuns.Cripto.main(Cripto.java:91)

ae está a classe, mas estou realizando testes…

package comuns;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//import javax.crypto.Cipher;
//import javax.crypto.SecretKey;
//import javax.crypto.SecretKeyFactory;
//import javax.crypto.spec.IvParameterSpec;
//import javax.crypto.spec.PBEKeySpec;
//import javax.crypto.spec.SecretKeySpec;
import com.sun.crypto.provider.*;//esses são direto do arquivo q baixei da sun... tem todas as classes comentadas acima
import javax.crypto.*;
import javax.crypto.spec.*;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class Cripto {
 private byte[] salt;
 private PBEKeySpec ks;
 private SecretKey skey;
 private SecretKeyFactory skf;
 public BASE64Decoder dec;
 public BASE64Encoder enc;

  public Cripto() {
    dec = new BASE64Decoder();
    enc = new BASE64Encoder();
 }

  public void senha(char[] chars) throws Exception {
 //System.out.println (System.getProperties());
   	  skf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    salt = new byte[4]; // deixamos 4 bytes zerados :(
    ks = new PBEKeySpec(chars, salt, 100, 128);
    skey = new SecretKeySpec(skf.generateSecret(ks).getEncoded(), "AES");
 }

  public String cifrar(String original) throws Exception {
    Cipher cf = Cipher.getInstance("AES/OFB/NoPadding", "SunJCE");
    cf.init(Cipher.ENCRYPT_MODE, skey, new IvParameterSpec(new byte[16]));
    return enc.encode(cf.doFinal(original.getBytes()));
 }

  public byte[] cifrarBytes(byte[] original) throws Exception {
    Cipher cf = Cipher.getInstance("AES/OFB/NoPadding", "SunJCE");
    cf.init(Cipher.ENCRYPT_MODE, skey, new IvParameterSpec(new byte[16]));
    return cf.doFinal(original);
 }

  public String decifrar(String cifrado) throws Exception {
    Cipher cf = Cipher.getInstance("AES/OFB/NoPadding", "SunJCE");
    cf.init(Cipher.DECRYPT_MODE, skey, new IvParameterSpec(new byte[16]));
    return new String(cf.doFinal(dec.decodeBuffer(cifrado)));
 }

  public byte[] decifrarBytes (byte[] bytes) throws Exception {
    Cipher cf = Cipher.getInstance("AES/OFB/NoPadding", "SunJCE");
    cf.init(Cipher.DECRYPT_MODE, skey, new IvParameterSpec(new byte[16]));
    return cf.doFinal(bytes);
 }


  private static byte[] serializar (Object obj) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream (baos);
    oos.writeObject(obj);
    oos.close();
    return baos.toByteArray();
 }
  private static Object desserializar (byte[] bytes) throws IOException, ClassNotFoundException {
    Object obj;
    ByteArrayInputStream bais = new ByteArrayInputStream (bytes);
    ObjectInputStream ois = new ObjectInputStream (bais);
    obj = ois.readObject();
    ois.close();
    return obj;
 }

  public static void main(String[] args) {
  try{
  	  Cripto ecs = new Cripto();
    ecs.senha("YjMIzg+3dhgc7a3EPoH/OA==".toCharArray());
    String s = ecs.cifrar("10/11/2010 - 18:06:45 - Local 3A - Profissional 2r");
   // Esperado: "6A63+uTkapyT8h9GNvYaklLyfIVUCxrCZ+7zIE9XRbJyt6f4i7jBs/13JvsLPNSHpm8="
    System.out.println(s);
    String t = ecs.decifrar(s);
    System.out.println(t);
   // Agora serializando uma lista de objetos.
    System.out.println ("Efetuando a serialização e desserialização");
    List<Object> list = new ArrayList<Object>();
    list.add (Integer.valueOf (12345678));
    list.add (Boolean.TRUE);
    list.add ("abacaxi");
    list.add (Math.PI);
    System.out.println ("Lista Original: " + list);
    BASE64Encoder enc = new BASE64Encoder (); 
    byte[] original = serializar(list);
    System.out.println ("Base-64 (original ): \n" + enc.encode (original));
    byte[] cifrado = ecs.cifrarBytes (serializar (list));
    System.out.println ("Base-64 (cifrado  ): \n" + enc.encode (cifrado));
    byte[] decifrado = ecs.decifrarBytes (cifrado);
    System.out.println ("Base-64 (decifrado): \n" + enc.encode (decifrado));
    System.out.println ("Original = Cifrado? " + Arrays.equals (original, decifrado));
    List<Object> listaDecifrada = (List<Object>) desserializar (decifrado);
    System.out.println ("Lista Decifrada: " + listaDecifrada);
}catch(Exception e){
e.printStackTrace();
}
   }

}

A zica é q nao roda no jre

up

Meu programa (não o seu - eu não o testei!) funciona direitinho com Java 5.0 e 6.0, dentro e fora do Eclipse. Realmente não sei o que pode ser.

A propósito, jce1_2_2.jar e o sunjce_provider.jar são versões muito antigas das APIs de criptografia, e não funcionam com o Java 5 ou 6.
Elas devem funcionar só com o Java 1.4. Por isso, você conseguiu compilar as coisas, mas não deve funcionar mesmo.
Nunca faça o que você fez - incluir diretamente as classes com.sun.algumacoisa.
Eu só pus algumas classes de sun.misc para facilitar, mas como a gente sempre diz, "faça o que eu digo, não faça o que eu faço :slight_smile: "

Pode ser que seu arquivo java.security esteja zoado por algum motivo. Se estiver, não vai achar os algoritmos mesmo. O meu arquivo java.security está assim (eu nunca o mexi, está como veio da instalação do JDK):

#
# This is the "master security properties file".
#
# In this file, various security properties are set for use by
# java.security classes. This is where users can statically register
# Cryptography Package Providers ("providers" for short). The term
# "provider" refers to a package or set of packages that supply a
# concrete implementation of a subset of the cryptography aspects of
# the Java Security API. A provider may, for example, implement one or
# more digital signature algorithms or message digest algorithms.
#
# Each provider must implement a subclass of the Provider class.
# To register a provider in this master security properties file,
# specify the Provider subclass name and priority in the format
#
#    security.provider.<n>=<className>
#
# This declares a provider, and specifies its preference
# order n. The preference order is the order in which providers are
# searched for requested algorithms (when no specific provider is
# requested). The order is 1-based; 1 is the most preferred, followed
# by 2, and so on.
#
# <className> must specify the subclass of the Provider class whose
# constructor sets the values of various properties that are required
# for the Java Security API to look up the algorithms or other
# facilities implemented by the provider.
#
# There must be at least one provider specification in java.security.
# There is a default provider that comes standard with the JDK. It
# is called the "SUN" provider, and its Provider subclass
# named Sun appears in the sun.security.provider package. Thus, the
# "SUN" provider is registered via the following:
#
#    security.provider.1=sun.security.provider.Sun
#
# (The number 1 is used for the default provider.)
#
# Note: Providers can be dynamically registered instead by calls to
# either the addProvider or insertProviderAt method in the Security
# class.

#
# List of providers and their preference orders (see above):
#
security.provider.1=sun.security.provider.Sun
security.provider.2=sun.security.rsa.SunRsaSign
security.provider.3=com.sun.net.ssl.internal.ssl.Provider
security.provider.4=com.sun.crypto.provider.SunJCE
security.provider.5=sun.security.jgss.SunProvider
security.provider.6=com.sun.security.sasl.Provider
security.provider.7=org.jcp.xml.dsig.internal.dom.XMLDSigRI
security.provider.8=sun.security.smartcardio.SunPCSC
security.provider.9=sun.security.mscapi.SunMSCAPI

#
# Select the source of seed data for SecureRandom. By default an
# attempt is made to use the entropy gathering device specified by 
# the securerandom.source property. If an exception occurs when
# accessing the URL then the traditional system/thread activity 
# algorithm is used. 
#
# On Solaris and Linux systems, if file:/dev/urandom is specified and it
# exists, a special SecureRandom implementation is activated by default.
# This "NativePRNG" reads random bytes directly from /dev/urandom.
#
# On Windows systems, the URLs file:/dev/random and file:/dev/urandom
# enables use of the Microsoft CryptoAPI seed functionality.
#
securerandom.source=file:/dev/urandom
#
# The entropy gathering device is described as a URL and can also
# be specified with the system property "java.security.egd". For example,
#   -Djava.security.egd=file:/dev/urandom
# Specifying this system property will override the securerandom.source 
# setting.

#
# Class to instantiate as the javax.security.auth.login.Configuration
# provider.
#
login.configuration.provider=com.sun.security.auth.login.ConfigFile

#
# Default login configuration file
#
#login.config.url.1=file:${user.home}/.java.login.config

#
# Class to instantiate as the system Policy. This is the name of the class
# that will be used as the Policy object.
#
policy.provider=sun.security.provider.PolicyFile

# The default is to have a single system-wide policy file,
# and a policy file in the user's home directory.
policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy

# whether or not we expand properties in the policy file
# if this is set to false, properties (${...}) will not be expanded in policy
# files.
policy.expandProperties=true

# whether or not we allow an extra policy to be passed on the command line
# with -Djava.security.policy=somefile. Comment out this line to disable
# this feature.
policy.allowSystemProperty=true

# whether or not we look into the IdentityScope for trusted Identities
# when encountering a 1.1 signed JAR file. If the identity is found
# and is trusted, we grant it AllPermission.
policy.ignoreIdentityScope=false

#
# Default keystore type.
#
keystore.type=jks

#
# Class to instantiate as the system scope:
#
system.scope=sun.security.provider.IdentityDatabase

#
# List of comma-separated packages that start with or equal this string
# will cause a security exception to be thrown when
# passed to checkPackageAccess unless the
# corresponding RuntimePermission ("accessClassInPackage."+package) has
# been granted.
package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.

#
# List of comma-separated packages that start with or equal this string
# will cause a security exception to be thrown when
# passed to checkPackageDefinition unless the
# corresponding RuntimePermission ("defineClassInPackage."+package) has
# been granted.
#
# by default, no packages are restricted for definition, and none of
# the class loaders supplied with the JDK call checkPackageDefinition.
#
#package.definition=

#
# Determines whether this properties file can be appended to
# or overridden on the command line via -Djava.security.properties
#
security.overridePropertiesFile=true

#
# Determines the default key and trust manager factory algorithms for 
# the javax.net.ssl package.
#
ssl.KeyManagerFactory.algorithm=SunX509
ssl.TrustManagerFactory.algorithm=PKIX

#
# The Java-level namelookup cache policy for successful lookups:
#
# any negative value: caching forever
# any positive value: the number of seconds to cache an address for
# zero: do not cache
#
# default value is forever (FOREVER). For security reasons, this
# caching is made forever when a security manager is set. When a security
# manager is not set, the default behavior is to cache for 30 seconds.
#
# NOTE: setting this to anything other than the default value can have
#       serious security implications. Do not set it unless 
#       you are sure you are not exposed to DNS spoofing attack.
#
#networkaddress.cache.ttl=-1 

# The Java-level namelookup cache policy for failed lookups:
#
# any negative value: cache forever
# any positive value: the number of seconds to cache negative lookup results
# zero: do not cache
#
# In some Microsoft Windows networking environments that employ
# the WINS name service in addition to DNS, name service lookups
# that fail may take a noticeably long time to return (approx. 5 seconds).
# For this reason the default caching policy is to maintain these
# results for 10 seconds. 
#
#
networkaddress.cache.negative.ttl=10

#
# Properties to configure OCSP for certificate revocation checking
#

# Enable OCSP 
#
# By default, OCSP is not used for certificate revocation checking.
# This property enables the use of OCSP when set to the value "true".
#
# NOTE: SocketPermission is required to connect to an OCSP responder.
#
# Example,
#   ocsp.enable=true
 
#
# Location of the OCSP responder
#
# By default, the location of the OCSP responder is determined implicitly
# from the certificate being validated. This property explicitly specifies
# the location of the OCSP responder. The property is used when the
# Authority Information Access extension (defined in RFC 3280) is absent
# from the certificate or when it requires overriding.
#
# Example,
#   ocsp.responderURL=http://ocsp.example.net:80
 
#
# Subject name of the OCSP responder's certificate
#
# By default, the certificate of the OCSP responder is that of the issuer
# of the certificate being validated. This property identifies the certificate
# of the OCSP responder when the default does not apply. Its value is a string 
# distinguished name (defined in RFC 2253) which identifies a certificate in 
# the set of certificates supplied during cert path validation. In cases where 
# the subject name alone is not sufficient to uniquely identify the certificate
# then both the "ocsp.responderCertIssuerName" and
# "ocsp.responderCertSerialNumber" properties must be used instead. When this
# property is set then those two properties are ignored.
#
# Example,
#   ocsp.responderCertSubjectName="CN=OCSP Responder, O=XYZ Corp"

#
# Issuer name of the OCSP responder's certificate
#
# By default, the certificate of the OCSP responder is that of the issuer
# of the certificate being validated. This property identifies the certificate
# of the OCSP responder when the default does not apply. Its value is a string
# distinguished name (defined in RFC 2253) which identifies a certificate in
# the set of certificates supplied during cert path validation. When this 
# property is set then the "ocsp.responderCertSerialNumber" property must also 
# be set. When the "ocsp.responderCertSubjectName" property is set then this 
# property is ignored.
#
# Example,
#   ocsp.responderCertIssuerName="CN=Enterprise CA, O=XYZ Corp"
 
#
# Serial number of the OCSP responder's certificate
#
# By default, the certificate of the OCSP responder is that of the issuer
# of the certificate being validated. This property identifies the certificate
# of the OCSP responder when the default does not apply. Its value is a string
# of hexadecimal digits (colon or space separators may be present) which
# identifies a certificate in the set of certificates supplied during cert path
# validation. When this property is set then the "ocsp.responderCertIssuerName"
# property must also be set. When the "ocsp.responderCertSubjectName" property
# is set then this property is ignored.
#
# Example,
#   ocsp.responderCertSerialNumber=2A:FF:00

No Linux e Solaris esse arquivo é um pouco diferente, mas não muito.

Cara, nem tem como t agradercer!

na verdade, a minha biblioteca jce tava zuada… acho q na vida loca eu troquei ela por outra ou sei lá… o fato é q qdo olhei, faltavam pacotes e tals… só me liguei disso qdo vc falou q a jce122 era velha, e realmente, eu tinha baixado do setor archived da sun… reinstalei o jdk e olhei a bilbioteca, foi só complilar e rodar… estou com problemas com bibliotecas, já deve ser minha terceira confusão por causa disso.

Tenho mais uma pergunta: a classe gera 2 chaves, uma publica e uma privada(?), qual eu mando pro cliente e como? creio q seja a chave criada pelas 2, pq o cliente precisará descriptografar coisas. Mas como enviar? qual o caminho seguro? envio o objeto chave?

Uma outra classe, não? Porque a que mostrei não usa chaves públicas e privadas.

huahuahuahuhuhuahuahuahuahua
tá certo! valeu memo!