2012-03-30 72 views
1

我有一个私钥和指数,我需要在android应用程序中实现字符串的RSA加密。 我该怎么做?有没有RSA加密的默认类?RSA加密与密钥和指数在android中

+0

的可能重复的[RSA加密:爪哇和Android之间的区别](http://stackoverflow.com/questions/6069369/rsa-encryption-difference-between-java-and- android) – Snicolas 2012-03-30 09:29:11

+0

但我不能使用这个PublicKey pubKey = readPublicKeyFromFile(mod,ex);在mod和ex变量中需要什么值,是字符串还是int? – praveenLal 2012-03-30 09:36:17

+0

我不同意@Snicolas,最重要的步骤是定义字符编码,并派生一个会话密钥会话密钥(或者,或者定义一个容器格式,如CMS)。这两个问题都没有涉及到这个问题。 – 2012-03-30 13:20:07

回答

2
public void saveToFile(String fileName, BigInteger mod, BigInteger exp) 
     throws IOException { 
    ObjectOutputStream oout = new ObjectOutputStream(
      new BufferedOutputStream(new FileOutputStream(fileName))); 
    try { 
     oout.writeObject(mod); 
     oout.writeObject(exp); 
    } catch (Exception e) { 
     throw new IOException("Unexpected error", e); 
    } finally { 
     oout.close(); 
    } 
} 

PublicKey ReadPublicKeyFromFile(String keyFileName) throws IOException { 
    InputStream in = RSACrypt.class.getClassLoader().getResourceAsStream(keyFileName); 
    ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
      in)); 
    try { 
     BigInteger m = (BigInteger) oin.readObject(); 
     BigInteger e = (BigInteger) oin.readObject(); 
     RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e); 
     KeyFactory fact = KeyFactory.getInstance("RSA"); 
     PublicKey pubKey = fact.generatePublic(keySpec); 
     return pubKey; 
    } catch (Exception e) { 
     throw new RuntimeException("Spurious serialisation error", e); 
    } finally { 
     oin.close(); 
    } 
} 

http://www.developpez.net/forums/d1001867/java/developpement-web-java/besoin-daide-rsa/

+0

这是用于任何文件加密,但我需要加密字符串,如用户名和密码 – praveenLal 2012-03-30 09:49:24

+0

不是真的,这是从文件加载/保存公钥,但我没有看到与您的问题的直接连接。 – 2012-03-30 13:16:15

+0

这是对问题作者评论的回答。在他关于readPubklicKey – Snicolas 2012-03-30 13:38:11