【问题标题】:Android encrypting string in android and decrypting in rubyAndroid在android中加密字符串并在ruby中解密
【发布时间】:2013-06-08 05:50:55
【问题描述】:

我使用此 (Android: decrypt RSA text using a Public key stored in a file) 作为指南,使用公钥加密“字符串”,然后使用 ruby​​ 中的私钥解密。

但是,我遇到了困难。部分原因是我在 Java 中加密字节,然后当我在 Ruby 中解密时,我没有翻译它。 我在下面附上Android sn-p:

        // reads the public key stored in a file
    AssetManager am = mContext.getAssets();
    InputStream is = am.open("public_key.pem");     
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    List<String> lines = new ArrayList<String>();
    String line = null;
    while ((line = br.readLine()) != null)
        lines.add(line);

    // removes the first and last lines of the file (comments)
    if (lines.size() > 1 && lines.get(0).startsWith("-----") && lines.get(lines.size()-1).startsWith("-----")) {
        lines.remove(0);
        lines.remove(lines.size()-1);
    }

    // concats the remaining lines to a single String
    StringBuilder sb = new StringBuilder();
    for (String aLine: lines)
        sb.append(aLine);
    String keyString = sb.toString();

    // converts the String to a PublicKey instance
    byte[] keyBytes = Base64.decode(keyString.getBytes("utf-8"), 0);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey key = keyFactory.generatePublic(spec);

    //byte[] encryptedText = null;
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    String encryptedText = Base64.encodeToString(cipher.doFinal(message), 0);

   return encryptedText;

我在 ruby​​ 中使用以下代码来尝试解码加密数据

pkey = OpenSSL::PKey::RSA.new private_key
print pkey.private_decrypt(Base64.decode64(android_encrypted_value))

在测试 Java 中生成的 base64 值与我在 ruby​​ 中另一个代码中生成的值不匹配时,我立即注意到了一个问题。 有什么想法吗?

【问题讨论】:

    标签: android encryption


    【解决方案1】:

    以下更改对我有用:

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING"); 
    cipher.init(Cipher.ENCRYPT_MODE, key); 
    String encryptedText = Base64.encodeToString(cipher.doFinal(message), Base64.DEFAULT);
    

    我能够将它应用到我的 Ruby 代码并使其工作。

    【讨论】:

      猜你喜欢
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      相关资源
      最近更新 更多