57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
package unicom
|
|
|
|
import (
|
|
"math/big"
|
|
"strings"
|
|
)
|
|
|
|
// encryptPassword 按登录脚本里的 RSAUtils.encryptedString 加密。
|
|
// 明文按字节放入 16 位小端 digit,再做模幂,输出不带空格分隔的十六进制块。
|
|
func encryptPassword(exponentHex, modulusHex, plain string) (string, error) {
|
|
modulus := new(big.Int)
|
|
if _, ok := modulus.SetString(modulusHex, 16); !ok || modulus.Sign() <= 0 {
|
|
return "", errBadKey
|
|
}
|
|
exponent := new(big.Int)
|
|
if _, ok := exponent.SetString(exponentHex, 16); !ok || exponent.Sign() <= 0 {
|
|
return "", errBadKey
|
|
}
|
|
chunk := 2 * highIndex(modulus)
|
|
if chunk < 2 {
|
|
return "", errBadKey
|
|
}
|
|
raw := []byte(plain)
|
|
for len(raw)%chunk != 0 {
|
|
raw = append(raw, 0)
|
|
}
|
|
parts := make([]string, 0, len(raw)/chunk)
|
|
for i := 0; i < len(raw); i += chunk {
|
|
block := new(big.Int)
|
|
for j := 0; j < chunk; j += 2 {
|
|
digit := int64(raw[i+j]) + int64(raw[i+j+1])<<8
|
|
block.Add(block, new(big.Int).Lsh(big.NewInt(digit), uint(j/2*16)))
|
|
}
|
|
crypt := new(big.Int).Exp(block, exponent, modulus)
|
|
parts = append(parts, hexBlock(crypt))
|
|
}
|
|
return strings.Join(parts, " "), nil
|
|
}
|
|
|
|
func highIndex(n *big.Int) int {
|
|
if n.Sign() == 0 {
|
|
return 0
|
|
}
|
|
return (n.BitLen() - 1) / 16
|
|
}
|
|
|
|
func hexBlock(n *big.Int) string {
|
|
h := n.Text(16)
|
|
if h == "" {
|
|
h = "0"
|
|
}
|
|
for len(h)%4 != 0 {
|
|
h = "0" + h
|
|
}
|
|
return h
|
|
}
|