88 lines
2.5 KiB
Go
88 lines
2.5 KiB
Go
package cryptoutil
|
|
|
|
import (
|
|
"testing"
|
|
)
|
|
|
|
func TestRSAKeyPair(t *testing.T) {
|
|
// 使用你提供的参数创建 RSA 密钥对
|
|
exponent := "10001"
|
|
modulus := "a1155dc73de04614604cbed62cc3b3198a639eb7b7d19cc2dfe3e787fe435f1464beee42a9a3cab6f1d3bfe66cd00317220ee770fd779b24c12c7698e251e875"
|
|
|
|
keyPair, err := NewRSAKeyPair(exponent, "", modulus)
|
|
if err != nil {
|
|
t.Fatalf("创建 RSA 密钥对失败: %v", err)
|
|
}
|
|
|
|
// 测试加密
|
|
plaintext := "241703070163"
|
|
ciphertext, err := keyPair.Encrypt(plaintext)
|
|
if err != nil {
|
|
t.Fatalf("加密失败: %v", err)
|
|
}
|
|
|
|
t.Logf("明文: %s", plaintext)
|
|
t.Logf("密文(十六进制): %s", ciphertext)
|
|
|
|
// 验证密文不为空
|
|
if len(ciphertext) == 0 {
|
|
t.Error("密文为空")
|
|
}
|
|
}
|
|
|
|
func TestRSAKeyPair_EncryptBytes(t *testing.T) {
|
|
exponent := "10001"
|
|
modulus := "a1155dc73de04614604cbed62cc3b3198a639eb7b7d19cc2dfe3e787fe435f1464beee42a9a3cab6f1d3bfe66cd00317220ee770fd779b24c12c7698e251e875"
|
|
|
|
keyPair, err := NewRSAKeyPair(exponent, "", modulus)
|
|
if err != nil {
|
|
t.Fatalf("创建 RSA 密钥对失败: %v", err)
|
|
}
|
|
|
|
// 测试字节加密
|
|
plaintext := []byte("Test data 测试数据")
|
|
ciphertext, err := keyPair.EncryptBytes(plaintext)
|
|
if err != nil {
|
|
t.Fatalf("字节加密失败: %v", err)
|
|
}
|
|
|
|
if len(ciphertext) == 0 {
|
|
t.Error("密文字节为空")
|
|
}
|
|
|
|
t.Logf("密文长度: %d bytes", len(ciphertext))
|
|
}
|
|
|
|
func TestNewRSAKeyPairFromPublicKey(t *testing.T) {
|
|
// 使用你提供的 X.509 格式的 base64 公钥
|
|
publicKey := "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCpbRy8ZoyQvRPpUDIXycglTwVDcYrLcv7P9HI4E7/TAPZiI3GN0ckTUVVWRvoo/re3uCOOJK+F+Ufh19XiRIdoPYCULsSyEjcLLiyAS09mVOzhAQco84E/lM24T7rRTVID7LIgWPewyN8Nd5vzHET4Q3qTthoL8n82BwC1iXuVQIDAQAB"
|
|
|
|
keyPair, err := NewRSAKeyPairFromPublicKey(publicKey)
|
|
if err != nil {
|
|
t.Fatalf("从公钥创建 RSA 密钥对失败: %v", err)
|
|
}
|
|
|
|
// 测试加密
|
|
plaintext := "241703070163"
|
|
ciphertext, err := keyPair.Encrypt(plaintext)
|
|
if err != nil {
|
|
t.Fatalf("加密失败: %v", err)
|
|
}
|
|
|
|
t.Logf("明文: %s", plaintext)
|
|
t.Logf("密文(十六进制): %s", ciphertext)
|
|
|
|
// 验证密文不为空
|
|
if len(ciphertext) == 0 {
|
|
t.Error("密文为空")
|
|
}
|
|
|
|
// 验证密文长度(1024位密钥应该产生128字节 = 256个十六进制字符)
|
|
expectedHexLen := (keyPair.GetModulus().BitLen() + 7) / 8 * 2
|
|
if len(ciphertext) != expectedHexLen {
|
|
t.Errorf("密文长度不正确: 期望 %d, 实际 %d", expectedHexLen, len(ciphertext))
|
|
}
|
|
|
|
t.Logf("密钥长度: %d bits", keyPair.GetModulus().BitLen())
|
|
}
|