scala - 加密字符串时生成数字

标签 scala encryption

我不是加密专家,但我需要从输入字符串生成一个数字并将其转换回原始字符串。

我在互联网上搜索了很多,但找不到任何人这样做。因此,我想向 StackOverflow 上的专家寻求帮助。

据我所知,将字符串加密为数字有点棘手,但我工作的项目要求这样做。

任何执行此操作的库或任何算法都可以解决我的问题。

这是我目前的代码

import java.security.MessageDigest
import java.util
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64


    object DataMaskUtil {

        def encrypt(key: String, value: String): String = {
          val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
          cipher.init(Cipher.ENCRYPT_MODE, keyToSpec(key))
           Base64.encodeBase64URLSafeString(cipher.doFinal(value.getBytes("UTF-8")))
        }

        def decrypt(key: String, encryptedValue: String): String = {
          val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING")
          cipher.init(Cipher.DECRYPT_MODE, keyToSpec(key))
          new String(cipher.doFinal(Base64.decodeBase64(encryptedValue)))
        }

        def keyToSpec(key: String): SecretKeySpec = {
          var keyBytes: Array[Byte] = (SALT + key).getBytes("UTF-8")
          val sha: MessageDigest = MessageDigest.getInstance("SHA-1")
          keyBytes = sha.digest(keyBytes)
          keyBytes = util.Arrays.copyOf(keyBytes, 16)
          new SecretKeySpec(keyBytes, "AES")
        }

         private val SALT: String =
        "jMhKlOuJnM34G6NHkqo9V010GhLAqOpF0BePojHgh1HgNg8^72k"

    }

使用 Maarten Bodewes 提供的想法

object Util2 {

  def encrypt(value: String): BigInteger = {
    val ct = value.getBytes()
    val abyte = 0x4D.toByte
    val byteBuffer = ByteBuffer.allocate(2+ct.length)
    byteBuffer.put(abyte).put(abyte)
    byteBuffer.put(ct)
    val number = new BigInteger(byteBuffer.array())
    number
  }

  def decrypt(ctAsNumber: BigInteger): String = {
    if (ctAsNumber.signum < 0 || ctAsNumber.bitLength < 15) throw new IllegalArgumentException("Magic of ciphertext number doesn't match")
    import java.nio.ByteBuffer
    val fixed = ByteBuffer.allocate((ctAsNumber.bitLength + java.lang.Byte.SIZE - 1) / java.lang.Byte.SIZE)
    fixed.put(ctAsNumber.toByteArray)
    fixed.flip()
    val ct = new Array[Byte](fixed.remaining())
    fixed.get(ct)
    new String(ct)
  }
}

当我测试函数时,输出在字符串前用“MM”填充

object MainClass {

      def main(args: Array[String]): Unit ={
        val encrypt = Util2.encrypt("Hi")
        println("The encrypted string is :: "+encrypt)

        val decrypt = Util2.decrypt(encrypt)
        println("The decrypted string is :: "+decrypt)

      }

    }

输出

The encrypted string is :: 1296910441
The decrypted string is :: MMHi

最佳答案

当然有多种方法可以做到这一点。但是让我们假设我们想要正值(通常是密码学要求的)并且我们希望结果适用于 ECB 和 CBC,但也适用于例如CTR模式加密。在那种情况下,我们还需要确保前导零得到妥善处理,因为前导零在密文中确实有意义,但对数字没有意义。

而且,这是一种在 JVM 上运行的语言,我们也将使用大端。

通过在左侧添加位/字节值,可以轻松避免负值和零字节。例如,我们可以使用众所周知的值,这也可以让您对密文数字的破坏有某种最低限度的保护。然后你会得到,在 Java 中:

private static BigInteger ciphertextToNumber(byte[] ct) {
    ByteBuffer fixed = ByteBuffer.allocate(2 + ct.length);
    fixed.put((byte) 0x4D).put((byte) 0x42);
    fixed.put(ct);
    BigInteger number = new BigInteger(fixed.array());
    return number;
}

private static byte[] numberToCiphertext(BigInteger ctAsNumber) {
    // if the number is negative then the buffer will be too small
    if (ctAsNumber.signum() < 0 || ctAsNumber.bitLength() < 15) {
        throw new IllegalArgumentException("Magic of ciphertext number doesn't match");
    }
    ByteBuffer fixed = ByteBuffer.allocate((ctAsNumber.bitLength() + Byte.SIZE - 1) / Byte.SIZE);
    fixed.put(ctAsNumber.toByteArray());
    fixed.flip();
    if (fixed.get() != (byte) 0x4D || fixed.get() != (byte) 0x42) {
        throw new IllegalArgumentException("Magic of ciphertext number doesn't match");
    }
    byte[] ct = new byte[fixed.remaining()];
    fixed.get(ct);
    return ct;
}

这是相对高效的,与密文相比,它不会增加太多可能的数字(因为密文可以有任何字节值,当然不可能压缩它)。一种优化方法是直接从 BigInteger 中提取魔法的字节值,但对于这种目的来说,多一份密文副本可能不会造成太大影响。

我会留给你转换成 Scala。


另一个想法是使用 RSA RFC 中定义的 I2OSP 或 OS2IP,但请注意,RSA 填充已经执行了相同类型的左填充,以确保字节数组到整数的转换得到妥善处理。此外,RSA 密文的大小始终与模数相同,而 AES 加密可能返回不同的大小。

关于scala - 加密字符串时生成数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671506/

相关文章:

scala - 使用 list 实例化 View 有界类型

java - Android KeyStore 系统 - 保存 key 对?

asp.net - 你能用 aspnet_regiis 加密整个 web.config 文件吗?

scala - 有没有办法让参数为 var 而不是 val?

java - 使用 play-scalr 会引发不支持的 Major.minor 版本 51.0

php - 如何使用 oauth 或类似模型通过序列/许可机制保护 PHP 代码以发出客户端 - 服务器请求?

ssl - H2 - 服务器模式下的拆分文件选项

.net - 如何检查 .NET 中是否存在 RSA key 容器

Scala:字符串压缩

list - 列表中的 Scala 与 F# 范围从 1 到 100000000